Search code examples
c++ifstream

ifstream does not work in Xcode?


I am attempting to work with some files using an ifstream. Everything appears to be fine, but when I attempt to open a file it will not work. Whether I attempt it as inputting a string variable or a string literal for the name. The files that I am attempting to access are in the same directory as the project and do contain contents.

The project does not display any errors and will compile, but it will just say that it can't access the file every time.

The additional headers, "simpio.h" and "console.h" are just 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!


Solution

  • 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 those values:

    GLIBCXX_DEBUG=1 
    GLIBCXXDEBUGPEDANTIC=1
    

    in the preprocessor macros.

    Older Xcode: image ! Newer Xcode:

    image!

    Example code:

    #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;
    }