Description: All rights reserved to the author, only for learning exchange, if there are other uses please contact the author, reproduced please follow IT professional norms, please indicate the address of the reprint
Five, getcwd function
getcwd function
function form
Char *getcwd (char *buffer, size_t size)
return value
Success
Failed
Whether to set errno
Returns a pointer to the current working directory string
Null
Is
Description: The GETCWD function obtains the current working directory, saves the working directory in the caller-supplied string, and the size of the string is assigned by the user.
Error message:
(1): The einval:size parameter is zero or the buffer is a null pointer.
(2): The erange:size parameter is less than the length of the current working directory, and more memory needs to be allocated.
(3): eacces: Insufficient permissions, no read or search file name permissions.
Practical Walkthrough:
From the explanation of the GETCWD function, we must allocate enough space for the buffer to get the result that the user expects. You can define a string of length Path_max to hold the current path. Path_max is an optional constant in the POSIX standard. This means that the variable may or may not be defined in the limits.h.
#include <iostream>
#include <limits.h>
#include <unistd.h>
#ifndef Path_max
#define PATH_MAX 1024
#endif
int main (void)
{
Char Cur_work_dir[path_max] = {' I '};
std:: cout << "Current Max Path Length is <<"
<< Path_max << Std::endl;
if (GETCWD (Cur_work_dir, path_max) = = NULL)
{
Perror ("couldn ' t get current working directory!");
return (1);
}
Std::cout << "Current Working Directory is:" <<cur_work_dir << Std::endl;
return (0);
}