-1

I would like to know if it is possible to open a directory and then work with fopen to open a file from it. Like in the example:

I have a MAINDIR and inside of it I have file.txt so I would like to do the following:

void openFile(const char * filename)
{
    opendir(MAINDIR);
    fopen(filename, "r");
}

int main()
{
   openFile("file.txt");
   return 0;
}

I know i could do: fopen("path/to/main/dir/filename.txt", "r") but i want something more generic. Open a directory and then make every fopen work inside that directory

Thanks

Cody
  • 484
  • 6
  • 20

4 Answers4

4

You can change your working directory using chdir(const char *) e.g:

chdir("/your/path/")
2

If you don't like messing around with chdir, you could just build the full path when you want to open the file:

void openFile(const char * filename)
{
    char fullpath[MAXPATHLEN];
    sprint( fullpath, "%s/%s", MAINDIR, filename );
    fopen( fullpath, "r" );
}

Although you probably want this to return something.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

opendir is for reading the content of a directory, that doesn't change the way relative paths are resolved. To change the starting point of relative paths you must use chdir:

chdir(MAINDIR);
...fopen(relative_path,...);
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
0

The opendir() function does not do what you want. Where available (which is not everywhere, as it is specified by POSIX, not C), it provides a means to read directory entries, but it does not affect filename resolution, which is always performed with respect to the current working directory, at least in implementations that provide opendir() in the first place.

On the other hand, POSIX environments provide chdir(), which changes the current working directory, and therefore the basis for resolving relative file names. That could achieve what you ask. Do note, however, that the working directory is a process-wide property. It is usually a better idea to construct and use either absolute paths or paths relative to the working directory, and to leave the working directory as whatever it is at program startup.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157