Search code examples
cfilefopenopendir

C - opendir + fopen


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


Solution

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

    chdir("/your/path/")