Ifstream not working in Xcode?

I am trying to work with some files using ifstream. Everything looks fine, but when I try to open the file, it will not work. I am trying to do this as inputting a string variable or string literal for a name. The files I am trying to retrieve are in the same directory as the project and contain the contents.

The project does not display any errors and compiles, but it just says that it cannot access the file every time.

The optional headers "simpio.h" and "console.h" are simply libraries provided by stanford.

#include <iostream> #include "console.h" #include "simpio.h" #include <fstream> #include <string> using namespace std; int countLines(ifstream & in) { int count = 0; while (true) { string line; getline(in, line); if (in.fail()) break; count++; } return count; } int main() { ifstream in; while (true) { cout << "Enter name: "; string s = getLine(); in.open(s.c_str()); if (!in.fail()) break; cout << "Couldn't open file, try again!" << endl; in.clear(); } cout << "Num lines = " << countLines(in) << endl; return 0; } 

Any help would be great! Thanks!

+4
source share
2 answers

You have two options:

1) Use Objective-C ++ (remove the .m extension and replace it with .mm)

2) Go to the project settings and add these values:

 GLIBCXX_DEBUG=1 GLIBCXXDEBUGPEDANTIC=1 

in preprocessor macros.

Old Xcode: image ! Newer Xcode:

image !

Code example:

 #include <iostream> #include <fstream> #include <string> using namespace std; int main(int argc, const char * argv[]) { ofstream myfile; myfile.open ("/Developer/afile.txt"); if(!myfile) { std::cout << "ERROR" std::endl; } myfile << "Writing this to a file.\n"; myfile.close(); return 0; } 
+3
source

If you don’t want to fit into Xcode, fearing that you might violate some other settings, do the following:

As soon as you create and run a console program or application, go to the list of files, usually on the left side, where the project is laid out, find the Projects directory, right-click or select Select and select Show in Finder. Here Xcode resets your builds every time you run it for this particular project. Each workspace will have its own build folder. You must find the file that you selected or created there if you want to add your own file, just drag it and then you can call it from the console or application program: myfile.open ("file.txt");

Or simply change the working directory for the project and use this folder, which is probably much more accessible than / Developer / Gibberish / Build / Debug / what.

This makes it easy to port your code to Win32 or other systems, at least for me.

+2
source

All Articles