0

Is there a way to set a search path for fopen() so that when I just enter the filename, it searches these path(s) for this file?

f=fopen("xxx","r");

I just want xxx not to be in the current directory, and I dont want to change the source code.

Keeto
  • 4,074
  • 9
  • 35
  • 58

2 Answers2

1

No, you have to code that yourself. If for any reason you can't change the code, you could change your filesystem, e.g. on Linux use symlinks, bind mounts, FUSE etc.

You could redefine fopen for your needs (but I recommend not doing this); on Linux you might even make it "transparent" with dirty LD_PRELOAD tricks.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

No, fopen only looks in the current directory, you can't give it a list of directories. But if you want it to search a list of paths:

char *paths[] = {
    ".",
    "/etc",
    "/usr/local",
    NULL
};

FILE *fp = NULL;
char path[ENOUGH];

while (!fp && paths[i]) {
    sprintf(path, "%s/%s", paths[i], name);
    fp = fopen(path, "r");

    i++;
}
cnicutar
  • 178,505
  • 25
  • 365
  • 392