fopen() function with a dynamic location i

2019-08-20 17:03发布

问题:

I just want to learn that how can I open a file with fopen() function from a dynamic location. I mean, for example it will be a system file and in another computer, this file can be in another location. So if I will set my location in my code not dynamically, my program will not work in another computer. So how Can I set the location dynamically for my program will find this file wherever it is?

回答1:

You can (and often should) pass program arguments to your main, thru the conventional int argc, char**argv formal arguments of your main. See also this.

(I am focusing on Linux, but you could adapt my answer to other OSes and platforms)

So you would use some convention to pass that file path (not a location, that word usually refers to memory addresses) to your program (often thru the command line starting your program). See also this answer.

You could use (at least on Linux) getopt_long(3) to parse program arguments. But there are other ways, and you can process the arguments of main explicitly.

You could also use some environment variable to pass that information. You'll query it with getenv(3). Read also environ(7).

Many programs have configuration files (whose path is wired into the program but often can be given by program arguments or by environment variables) and are parsing them to find relevant file paths.

And you could even consider some other inter-process communication to pass a file path to your program. After all, a file path is just some string (with restrictions and interpretations explained in path_resolution(7)). There are many ways to pass some data to a program.

Read also about globbing, notably glob(7). On Unix, the shell is expanding the program arguments. You may want to use functions like glob(3) or wordexp(3) on something obtained elsewhere (e.g. in some configuration file) to get similar expansion.

BTW, be sure, when using fopen, to check against its failure. You'll probably use perror like here.

Look also into the source code of several free software projects (perhaps on github) for inspiration.



回答2:

I would suggest you to use the environment variables, In a PC set your file location as environment variable. then read the environment variable value in your program, then open the file. This idea works both in linux and windows however you have adopt the code based on the OS to read the environment variables.



回答3:

Besides specifying file location at runtime through command line arguments, environment variables or configuration files, you can implement a PATH-like logic:

  • Possible locations for your file are set in an environment variable:

    export MY_FILE_PATH=/usr/bin:/bin:/opt/bin:$HOME/bin
    
  • Your program reads that environment variable, parses its contents and checks existence of file in each specified path, with fopen() return status.



标签: c file fopen