1. 获取当前目录
#include <unistd.h>
char * getcwd (char *buf, size_t size);
==>例程:获取当前目录(POSIX版本)
char cwd[BUF_LEN];
if (!getcwd (cwd, BUF_LEN)) {
perror ("getcwd");
exit (EXIT_FAILURE);
}
printf ("cwd = %s\n", cwd);
==>例程:获取当前目录(linux版本)
char *cwd;
cwd = getcwd (NULL, 0);
if (!cwd) {
perror ("getcwd");
exit (EXIT_FAILURE);
}
printf ("cwd = %s\n", cwd);
free (cwd);
#include <unistd.h>
int chdir (const char *path);
int fchdir (int fd);
==>例程:改变当前目录与恢复
The most common use of getcwd() is to save the current working directory so that the process can return to it later. For example:
char *swd;
int ret;
/* save the current working directory */
swd = getcwd (NULL, 0);
if (!swd) {
perror ("getcwd");
exit (EXIT_FAILURE);
}
/* change to a different directory */
ret = chdir (some_other_dir);
if (ret) {
perror ("chdir");
exit (EXIT_FAILURE);
}
/* do some other work in the new directory... */
/* return to the saved directory */
ret = chdir (swd);
if (ret) {
perror ("chdir");
exit (EXIT_FAILURE);
}
free (swd);
另一个更高效的版本:
int swd_fd;
swd_fd = open (".", O_RDONLY);
if (swd_fd == −1) {
perror ("open");
exit (EXIT_FAILURE);
}
/* change to a different directory */
ret = chdir (some_other_dir);
if (ret) {
perror ("chdir");
exit (EXIT_FAILURE);
}
/* do some other work in the new directory... */
/* return to the saved directory */
ret = fchdir (swd_fd);
if (ret) {
perror ("fchdir");
exit (EXIT_FAILURE);
}
/* close the directory's fd */
ret = close (swd_fd);
if (ret) {
perror ("close");
exit (EXIT_FAILURE);
}
通过利用fd,内核可以直接操纵inode,所以效率更高。
3. 创建目录
#include <sys/stat.h>
#include <sys/types.h>
int mkdir (const char *path, mode_t mode);
#include <unistd.h>
int rmdir (const char *path);
仅对空目录有才会成功
5. 读取目录内容
#include <sys/types.h>
#include <dirent.h>
DIR * opendir (const char *name);
DIR是一个目录流
5.1 读取目录流
#include <sys/types.h>
#include <dirent.h>
struct dirent * readdir (DIR *dir);
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file */
char d_name[256]; /* filename */
};
5.2 关闭目录流
#include <sys/types.h>
#include <dirent.h>
int closedir (DIR *dir);
==>例程:查找目录中是否有特定的文件
/*
* find_file_in_dir - searches the directory 'path' for a
* file named 'file'.
*
* Returns 0 if 'file' exists in 'path' and a nonzero
* value otherwise.
*/
int find_file_in_dir (const char *path, const char *file)
{
struct dirent *entry;
int ret = 1;
DIR *dir;
dir = opendir (path);
errno = 0;
while ((entry = readdir (dir)) != NULL) {
if (strcmp(entry->d_name, file) == 0) {
ret = 0;
break;
}
}
if (errno && !entry)
perror ("readdir");
closedir (dir);
return ret;
}