Since C it’s not a language I am used to program with, I don’t know how to do this.
I have a project folder where I have all the .c and .h files and a conf folder under which there is a config.txt file to read. How can I open that?
FILE* fp = fopen("/conf/config.txt", "r");
if (fp != NULL)
{
//do stuff
}
else
printf("couldn't open file\n");
I keep getting the error message. Why?
Btw, this only have to work on windows, not linux.
Thanks.
The easy way is to use an absolute path…
Or you can use a relative path. If your executable is in
/home/me/binand your txt file is in/home/me/doc, then your relative path might be something likeThe important thing to remember in relative paths is that it is relative to the current working directory when the executable is run. So if you used the above relative path, but you were in your
/tmpdirectory and you ran/home/me/bin/myprog, it would try to open/tmp/../doc/my_file.txt(or/doc/my_file.txt) which would probably not exist.The more robust option would be to take the path to the file as an argument to the program, and pass that as the first argument to
fopen. The simplest example would be to just useargv[1]frommain‘s parameters, i.e.Of course, you’ll want to put in error checking to verify that
argc> 2, etc.