0

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!

Rohan
  • 541
  • 1
  • 11
  • 24

2 Answers2

1

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.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you very much. Is there any way I can make it so that it reads from the same directory as the program itself? – Rohan Jan 23 '14 at 04:50
0

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

Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137
  • The same directory as the source code right? Because I have the file there, but `fopen()` keeps returning `NULL`. – Rohan Jan 23 '14 at 04:40
  • @Rohan I just tried your code also, it does not return NULL. Please let me repeat, in your case you should keep files where you have .c/.cpp files. – Pranit Kothari Jan 23 '14 at 04:43
  • This is wrong. The source code is irrelevant, pathnames are interpreted relative to the user's working directory. – Barmar Jan 23 '14 at 04:45
  • @Barmar I am using Visual Studio and code is working fine if I keep txt file in source code folder. – Pranit Kothari Jan 23 '14 at 04:49
  • That sounds very specific to VS, it's not a general solution. – Barmar Jan 23 '14 at 04:52