tags:

views:

40

answers:

3

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.

+3  A: 

The easy way is to use an absolute path...

my_file = fopen("/path/to/my/file.txt", "r");

Or you can use a relative path. If your executable is in /home/me/bin and your txt file is in /home/me/doc, then your relative path might be something like

my_file = fopen("../doc/my_file.txt", "r");

The 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 /tmp directory 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 use argv[1] from main's parameters, i.e.

int main(int argc, char **argv)
{
    FILE *my_file = fopen(argv[1], "r");
    /* ... */
    return 0;
}

Of course, you'll want to put in error checking to verify that argc > 2, etc.

Mark Rushakoff
I need to use a relative path. I have the file in conf folder and have tried FILE* fp = fopen("/conf/config.txt", "r") and that didn't worked.
nunos
@nunos: That is not a relative path. A relative path begins with either `.` indicating the current working directory, or `..` indicating the directory *above* the current working directory. That is to say, if you are in `/tmp/foo`, then `.` refers to `/tmp/foo` while `..` refers to `/tmp`. Then `./bar.txt` would indicate `/tmp/foo/bar.txt`.
Mark Rushakoff
I am working in windows. Is that true to windows too?
nunos
@nunos: Yes, the relative directory syntax is the same in Windows and Unix.
Mark Rushakoff
A: 

You're probably going to want to look into the dirent family of routines for directory traversal.

genpfault
A: 

The location of your .c and .h files is not really the issue; the issue is the current working directory when you run your executable.

Can you not pass in the full path to the fopen() function?

Simon Nickerson