Int chdir (const char * path );
Note: The chdir function is used to change the current working directory. The call parameter is a pointer to a directory. The call process must have the permission to search the entire directory. Each process has a current working directory. When parsing relative directory references, this directory is the start of the search path. If the called process changes the directory, it is only valid for the process, and does not affect the process that calls it. When you exit the program, shell will return the working directory at the beginning.
(1) The path name in the kernel resolution parameter and make sure the path name is valid. To achieve this, the kernel uses the same algorithm for path name resolution. If the path name is invalid, it outputs an error message and exits.
(2) If the path name is valid, the kernel locates the index node of the Directory and checks its file type and permission bit, make sure that the target file is a directory and the owner of the process can access the directory (otherwise it will be useless if it is changed to a new directory ).
(3) The kernel replaces the path name of the current directory and/or its index node in the U area with the path name of the new target directory.
Error message:
Efault: path points to an Invalid Address.
Enamounlng: the path is too long.
Enoent: the file does not exist.
Enomem: insufficient kernel memory
Enotdir: The given path is not a directory
Eacces: You do not have permission to access a directory in the path.
Eloop: parse too many symbolic links in the path
EIO: an I/O error occurs.
Instance 1:
/* Chdir. C: This program using chdirr */
# Include <unistd. h>
# Include <iostream>
Int main (void)
{
Long cur_path_len;
Char * cur_work_dir;
If (cur_path_len = pathconf (".", _ pc_path_max) =-1)
{
Perror ("couldn't get currentworking path length ");
Return 1;
}
STD: cout <"current path lengthis" <cur_path_len <STD: Endl;
If (cur_work_dir = (char *) malloc (cur_path_len) = NULL)
{
Perror ("couldn't allocate memoryfor the pathname ");
Return 1;
}
If (getcwd (cur_work_dir, cur_path_len) = NULL)
{
Perror ("couldn't get currentworking directory! ");
}
Else
{
STD: cout <"currentworking directory is" <cur_work_dir <STD: Endl;
}
If (chdir ("..") =-1)
{
Perror ("couldn't change current working diretory! ");
Return 1;
}
If (getcwd (cur_work_dir, cur_path_len) = NULL)
{
Perror ("couldn't get currentworking directory! ");
Return 1;
}
STD: cout <"afterchangedirectory, current working directory is" <cur_work_dir <STD: Endl;
Free (cur_work_dir );
Return 0;
}