0

I'm having trouble opening a file using fopen in C++. I'm using XCode 4. Here's my code:

FILE *f;
f = fopen("test.txt", "r"); 
if (f == NULL)
   std::cout << "Error: NULL file";

When I run this, the error message gets printed. test.txt is stored in the same directory as my XCode project. I just want to be able to read from test.txt hence the "r."

Any tips? Thanks.

2
Contributors
2
Replies
5
Views
5 Years
Discussion Span
Last Post by binningen
0

test.txt is stored in the same directory as my XCode project.

But is that the current working directory for XCode (assuming you're running directly from the IDE)? Use perror() to get a more useful error message:

FILE* f = fopen("test.txt", "r");

if (f == NULL)
    std::perror("Error opening file");

I suspect the error will be something along the lines of "File not found", which suggests that XCode is looking in the wrong place. I'm not familiar with XCode, but there's probably a build or debug folder where the executable lives, and that's likely where text.txt should be placed.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.