Can't open text file in Xcode

I've got some problems trying to read a text file. I don't know where my compiler looks for the file and I guess that's what's causing the problem. I simply used the sample code from this tutorial: http://www.cplusplus.com/doc/tutorial/files/
Except that my file is called Untitled, but has the same content as the example.txt file in the tutorial, and it's located in the folder of my c++ project.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main () {
    string line;
    ifstream myfile ("Untitled.rtf");
    if (myfile.is_open())
    {
        while ( getline (myfile,line) )
        {
            cout << line << endl;
        }
        myfile.close();
    }
    
    else cout << "Unable to open file";
    
    return 0;
}


I get Unable to open file as output. How do I have to refer to text files on OS X in case it's different from other operating systems, do I have to include the txt ending? Where do I have to locate files in order for my compiler to find it and how does the search process of a compiler work?

EDIT: Just noticed that my file is a Rich Text File, not simply a text file. But if I try to refer to it via .rtf it won't work either.

EDIT2: So after figuring out how to create txt files on a mac, I tried the same version with a txt file, but still get Unable to open file as output.
Last edited on
closed account (o3hC5Di1)
Hi there,

The file is searched for in the path you pass to the std::ifstream constructor, in your case there is only the filename so the program looks in the same folder as it is located itself.

Is the text file in the same folder as your program is running in?

All the best,
NwN
Thanks for your answer.

Yes the text file is in the same folder as the program file.
Topic archived. No new replies allowed.