Question

I'm trying to open files in a C program, but I am unsure where to place the files I want to open (as in which directory). Here is the code, but I really just need to know where to place the file I want to open with fopen().

FILE *fileptr;

fileptr = fopen("QuizQuestions.txt", "r");
if (fileptr == NULL) {
    printf("Unable to open file.");
}

Any help is appreciated!

Was it helpful?

Solution

If you don't use an absolute pathname in your code, paths are interpreted relative to the working directory of the user when they run the program. So for your program, the user should put the file in their current directory.

The location of the program itself is irrelevant. If you want to get the location of the program, you see this question:

How do I find the location of the executable in C?

You can then concatenate the directory with the filename.

OTHER TIPS

You need to keep files where source code file is placed.Otherwise, you need to give absolute path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top