How to get the absolute path of the configuration file in Linux

  

Linux programs usually have configuration files, if the configuration file uses a relative path, for example: "../src/config.xml"

then at the current Under the path, there is no problem with the execution;

If you switch to another path, there will be problems with the execution and the file cannot be found;

When writing the script, you must first cd to the executable file. Path, and then execute;

If you want to eliminate this effect, you can not write the dead path, then you need to transform the relative path into an absolute path;

Step:

1. First, get the path where the program is located;

2. Add the relative path, then get the absolute path;

Please note: not the current path, getcwd can get the current path; Not the absolute path of the program; I made this mistake at the time!

The following describes how to get the path where the program is located:

Method 1. If you don't care about possible security risks, you can use procfs, then readlink, to put the current process's pid corresponding to the directory below. The location pointed to by file is read out (note that you need to mount procfs first)

pit_t mypid = getpid();

sprintf(strsrc, "/proc/%d/file", mypid);

readlink(strsrc, strdest, LEN);//LEN is best your _POSIX_PATH_MAX

Method 2. Use the realpath function, then dirname; finally splicing out the absolute path of the configuration file; Br>

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);

Copyright © Windows knowledge All Rights Reserved