linux系统编程之文件与IO(四):目录访问相关系统调用
linux系统编程之文件与IO(四):目录访问相关系统调用
1. 目录操作相关的系统调用
1.1 mkdir和rmdir系统调用
1.1.1 实例
1.2 chdir, getcwd系统调用
1.2.1 实例
1.3 opendir, closedir, readdir,
1.3.1 实例:递归便利目录
1. 目录操作相关的系统调用
1.1 mkdir和rmdir系统调用
[code]
filename: mk_rm_dir.c
#include <sys/stat.h>
int mkdir(const char *path, mode_t mode);
return:
S 0
F -1
note:
mode权限至少要有执行权限。
[/code]
[code]
#include <unistd.h>
int rmdir(const char *pathname);
return:
S 0
F -1
note:
pathname目录必须是空目录。
1.1.1 实例
#include <unistd.h><sys/stat.h><stdio.h><assert.h>
MODE (S_IRUSR | S_IWUSR | S_IXUSR | S_IXGRP | S_IXOTH)
main( argc, * *== = argv[== ==
测试:
[qtlldr@qtldr editing]$ ./mk_rm_dir testdir
create testdir successful!
rm testdir
[qtlldr@qtldr editing]$
1.2 chdir, getcwd系统调用
#include <unistd.h>
int chdir(const char *pathname);
return:
S 0
F -1
#include <unistd.h>
char *getpwd(char *buf, size_t size);
return:
S buf
F NULL
buf是缓冲地址,size是buf的长度。该缓冲必须有足够的长度以容纳绝对路径名加上一个null终止符。
1.2.1 实例
[code]
filename:ch_get_dir.c
#include <unistd.h><stdio.h><.h><assert.h>
BUFSIZE (50)
main( *)buf, , ) == !=
测试:
[qtlldr@qtldr editing]$ ./ch_get_dir
chdir to /tmp successful
now the directory is /tmp
[qtlldr@qtldr editing]$
1.3 opendir, closedir, readdir,
#include <sys/type.s>
#include <dirent.h>
DIR *opendir(const char *dirname);
return:
S DIR指针
F NULL
note:
DIR是一种目录结构,类似FILE。
#include <sys/types.h>
#include <dirent.h>
struct dirent *readir(DIR *dirp);
return:
S 一个指向保存目录流下一个目录项的dirent指针
F NULL
note:
struct dirent {
char d_name[NAME + 1]; /* \0结尾的文件名 */
}
到达目录尾或出错返回NULL,但是到达目录尾不会设置errno,出错则设置。
如果在readir的同时有其他进程在目录中创建或者删除文件爱你,readdir不保证能列处该目录中所有文件。
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
return:
S 0
F -1
1.3.1 实例:递归便利目录
filename:help.txt 帮助文档
本程序只为学习linux目录操作而写
printdir
输出目录文件或者统计目录中的文件数目
语法:
printdir [option] <files...>
选项:
-l
输出目录下的文件名
-c
统计目录下的文件
-d n
指定最大层次,最大为30
默认行为:
如果没有指定选项,那么只输出该目录下的文件名
BUG:
-l与 -c选项不能同时使用,如果同时使用统计出错。(以后会修正)
本程序只为学习linux目录操作而写
filename:printdir.c
#include <unistd.h><fcntl.h><sys/stat.h><sys/types.h><dirent.h><stdio.h><.h><stdlib.h>
INDENT_DEPTH (4) /* 列举文件时的缩进数 */
DEPTH_MAX (30) /* 递归便利的最大层次 */
HELPFILE ("help.txt")
DEPTH = ;
idepth_count = idepth_print = nfiletype *count_files( * nfiletype * printdir( *pathname, main( argc, ** count_flag = print_flag = *parg = nfiletype nfiles = { *filename_help = ((opt = getopt(argc, argv, )) != - = = = strtol(optarg, NULL, = depth_opt <= DEPTH_MAX ? = (fd_help != - ((nread_help = read(fd_help, buf_help, BUFSIZ)) >
(!print_flag && != ( ; optind < argc; optind++=
printdir(parg, *)&nfiles, ,
count_files(parg, &
nfiletype *count_files( * nfiletype ** dirent *
(idepth_count >++ ((dp = opendir(pathname)) ==