Talk C chestnuts together (58th back: C language instance -- get the current working path of the Program)
Dear valued officers, we are talking about the example of the main function parameter in the last time. This example is used to obtain the current state of the program.
. When you leave the rest of your time, your words will go right. Let's talk C chestnuts together!
At work, we sometimes need to obtain the working path of the current program. Do you remember the Linux commands we mentioned before?
In Linux, a command called pwd can display the current working path.
The following is a demonstration:
Open the terminal, enter the pwd command in the current working path, and press enter to execute the command. The command execution result is as follows:
/Home/talk8/CExample // display the current working directory
I don't know what the audience did. We run the pwd command on the terminal to get the current working directory. if you want
How can I get the current working directory?
There must be a solution. We can implement it through the execlp () function. Execlp functions call terminals to execute the commands passed to them.
Specific usage:Execlp (cmd, cmd, params, char * p ).
Cmd indicates the commands that can be executed on the terminal. params is the cmd parameter. p is usually not used. You can assign it to 0. This function has a return value. If a command is not supported by the terminal, it returns-1, indicates that the command cannot be executed or the command fails to be executed.
In addition to the above method, the Linux system also provides us with a dedicated API: getcwd. Through it, we can get the current work
Directory.
Specific usage:Getcwd (char * buf, int size ).
Buf is used to store the obtained working path. size indicates the size of the buf.
The readers will not write the code in the body, and the detailed code will be put into my resources. You can click here to download and use it.
The following is the running result of the program. For details, refer:
. /S // run the program Current directory in the terminal is:/home/talk8/CExample // obtain the Current working directory through the API. /s pwd // run the program on the terminal. The second parameter is pwd, which indicates that the program executes the pwd command/home/talk8/CExample // to obtain the current working directory through execlp. /s a // run the program on the terminal. The second parameter is a, which indicates that the program executes command a: command not found. // command a cannot be executed. /s a // run the program on the terminal. Parameters 2, 3, and 4 are both a, indicating that the program can execute the command two worker params // The a command cannot be executed.
Let's talk about the example of getting the current working path of a program. I want to know what examples will be provided later, and I will try again.