Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open method opens files with full path only C++

File opens if I write the full path (full-path/roots.txt). File fails to open if I write the filename only (roots.txt)

And yet, roots.txt is in the same folder as the main.cpp. Is there any settings I should check on XCode?

Here's the code:

    string line;
ifstream infile;
infile.clear();
// infile.open("roots.txt");
infile.open("/Users/programming/C++/roots/roots.txt");
if (infile.fail()) cout << "could not open the file: " << strerror(errno);
getline(infile, line);
cout << line;
like image 531
JohnG Avatar asked Jun 13 '26 09:06

JohnG


2 Answers

By default, Xcode working directory is something like ~/Library/Developer/Xcode/DerivedData/project-/Build/Products/Debug. So,if you are trying to use a relative path with respect your project directory or any other, you should manually configure your working directory in Xcode.

You can do this by: Product -> Scheme -> Edit Scheme -> options tab, tick the use custom working directory checkbox and show your path.

like image 168
Kaje Avatar answered Jun 14 '26 23:06

Kaje


If it works when you attempt to open a file with an absolute path and fails with just the filename, your relative path is likely incorrect. Ensure roots.txt is placed in the current working directory. Look into the getcwd function declared in unistd.h.

like image 44
James Avatar answered Jun 14 '26 21:06

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!