Article Title: Linux programs eliminate the influence of relative file paths. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
Linux usually has a configuration file. If the configuration file adopts a relative path, for example, "../src/config. xml"
The execution in the current path is normal;
If you change to another path, the execution fails and the file cannot be found;
When writing a script, you must first cd it to the path of the execution file and then execute it;
If you want to eliminate this impact and cannot write a dead path, you need to change the relative path to an absolute path;
Steps:
1. First, obtain the path of the program;
2. Add the relative path to obtain the absolute path;
Note: if it is not the current path, getcwd can obtain the current path, rather than the absolute path of the program. I made this mistake at the time!
The following describes how to obtain the path of a program:
Method 1. If you do not care about potential security risks, you can use procfs and readlink to read the file pointing to the directory corresponding to the pid of the current process (note that you must first Mount procfs)
Pit_t mypid = getpid ();
Sprintf (strsrc, "/proc/% d/file", mypid );
Readlink (strsrc, strdest, LEN); // your _ POSIX_PATH_MAX is the best.
Method 2: Use the realpath function, then dirname, and finally splice the absolute path of the configuration file;
Char path [PATH_MAX];
Char * rpath = realpath (argv [0], path );
LOG_IT (LOG_MAIN, LOG_DEBUG, "argv [0]: % s, realpath % s", argv [0], rpath );
Char * base = basename (path );
Char * dir = dirname (path );
LOG_IT (LOG_MAIN, LOG_DEBUG, "base: % s, dir % s", base, dir );
Char conf_file [2048];
Int maxlen_conf = 2048;
Snprintf (conf_file, maxlen_conf, "% s/% s", dir, "../src/config. xml ");
LOG_IT (LOG_MAIN, LOG_DEBUG, "conf_file % s", conf_file );