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.

Recommended Answers

All 2 Replies

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.

Too true. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.