If you need to read the configuration file in the program you are writing, or if you need to print the log file, or read another file, a problem occurs:
What path does the executable program use when reading the file path?
The structure of our general project is:
project/
bin/executable Location
conf/Configuration file Location
log/Log File location
include/Header File Location
src/Source file Location
obj/Temporary project file location, i.e.. o File
other/some other files
So when we write the program, we usually use the relative path to read the configuration file, or the location of the log file, because the structure of the project is fixed, so that the whole project is migrated to another place is easier to handle, no error.
However, use relative paths, such as FP = open (".. /log/program.log "); Poses a problem if the executable program is called by a script other than the project directory, then the executable is in the location of the shell script, not the project/bin/directory, and of course those relative log,conf The path also does not exist.
Therefore, when you write the program should get the original location of the executable program, when using other files in the file path to add the executable program's absolute path, so that the executable can be properly accessed to the relative path of the log file, and so on.
stringGetownerpath () {Charpath[1024x768]; intCNT = Readlink ("/proc/self/exe", Path,1024x768); if(CNT <0|| CNT >=1024x768) { returnNULL; }//The last '/' is followed by the executable name, minus the name of the executable program, leaving only the path for(inti = CNT; I >=0; --i) {if(path[i]=='/') {Path[i+1]=' /'; Break; } } stringS_path (path); Here I turn char into a string type for ease of handlingreturnS_path;}
When the corresponding log file is read, it can be written as:
voidLog (string&s_message) {Ofstream logfile; stringPath =Getownerpath (); Gets the absolute path location of the executable program path+=".. /log/program.log"; Stitching path to get the absolute path of log file Logfile.open (Path.c_str (), Ios::app); if(Logfile.is_open ()) {Logfile.write (S_message.c_str (), s_message.size ()); } Else{cout<<"cannot open log file, please check its path!"<<Endl; } logfile.close (); }
Absolute path to get executable program under Linux