Unable to open a file with fopen()

jet picture jet · Nov 17, 2009 · Viewed 114.6k times · Source

I've been trying to open a file and output text, but I keep getting errors. So I thought I would start at the very beginning and just try opening the file. This is my code:

#include <stdio.h>
#include <stdlib.h>
#define CORRECT_PARAMETERS 3

int main(void)
{
    FILE *file;
    file = fopen("TestFile1.txt", "r");
    if (file == NULL) {
        printf("Error");
    }
    fclose(file);
}

When I run the file, "Error" gets printed to the console and that's it. The TestFile1.txt is in the same location as my .exe. How do I fix this?

Answer

Kousik Nandy picture Kousik Nandy · Nov 17, 2009

Instead of printf("Error");, you should try perror("Error") which may print the actual reason of failure (like Permission Problem, Invalid Argument, etc).