Unix环境高级编程(二)文件和目录

  本章主要介绍的是文件结构及目录。重点是通过stat函数获取文件的结构信息,然后是文件目录及其遍历。学完本章后,编写了一个输出给的目录下的文件信息的程序。

首先是包含在<sys/stat.h>文件下的stat、fstat、lstat三个函数,三个函数的原型如下:

int stat(const char *path, struct stat *buf);
int fstat(int
fd, struct stat *buf);
int lstat(const char *
path, struct stat *buf);

三个函数的返回值:成功返回0,出错返回-1。

三个函数的区别如下:

stat() stats the file pointed to by path and fills in buf.

lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.

fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.

第二个参数buf是个指针,指向一个文件的具体信息。

struct stat {
    dev_t         st_dev;     /* ID of device containing file */
    ino_t          st_ino;     /* inode number */
    mode_t      st_mode;    /* protection */
    nlink_t       st_nlink;   /* number of hard links */
    uid_t         st_uid;     /* user ID of owner */
    gid_t         st_gid;     /* group ID of owner */
    dev_t        st_rdev;    /* device ID (if special file) */
    off_t          st_size;    /* total size, in bytes */
    blksize_t      st_blksize; /* blocksize for file system I/O */
    blkcnt_t     st_blocks;  /* number of 512B blocks allocated */
    time_t       st_atime;   /* time of last access */
    time_t       st_mtime;   /* time of last modification */
    time_t       st_ctime;   /* time of last status change */
};

Unix下的文件类型有:普通文件(regular file),目录文件(directory file),块特殊文件(block
special file),字符特殊文件(character special
file),FIFO,套接字(socket),符号链接(symbolic link)。

通过stat系类函数可以判断一个文件是否存在,获取文件的相关信息,例如文件类型、文件长度。

Unix中只有内核才能写目录,对某个目录具有访问权限的任一个用户都可以读该目录。

在头文件<dirent.h>中,提供有一系类目录操作函数。

DIR *opendir(const char *name);

struct dirent *readdir(DIR *dirp);

void rewinddir(DIR *dirp);

int closedir(DIR *dirp);

dirent结构如下:

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; not supported
                                   by all file system types */
    char           d_name[256]; /* filename */
};

现在写个小程序,巩固函数的运用。程序的功能是:给定一个目录,输出该目录下所有目录及文件信息。程序如下:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <unistd.h>
 4 #include <sys/stat.h>
 5 #include <dirent.h>
 6 #include <string.h>
 7 #include <errno.h>
 8  9 void    showallfile(char* filepath);

11 int main(int argc,char* argv[])
12 {
13     if(argc != 2)
14     {
15         printf("Error.Please input filepath.\n");
16         exit(-1);
17     }
18    //argv[1]中是目录参数
19     showallfile(argv[1]);
20     return 0;
21 }
22
23 void showallfile(char* filepath)
24 {
25     struct stat st;
26     DIR *dp;
27     struct dirent* dirp;
28     char *pstr;
29    //获取文件信息
30     if(lstat(filepath,&st) == -1)
31     {
32        perror("lstat() error");
33        exit(-1);
34     }
35     //判断文件是否是目录文件
36     if(S_ISDIR(st.st_mode) == 0)  //不是
37       printf("File: %s\n",filepath);
38     else                          //是目录文件,需要进行读目录操作
39     {
40         printf("Directory: %s\n",filepath);
41         pstr = filepath+strlen(filepath);
42         *pstr++ = ‘/‘;
43         *pstr = 0;
44         //打开目录
45         if((dp = opendir(filepath)) == NULL)
46         {
47             printf("opendir() error");
48             exit(-1);
49         }
50        //读取该目录下的内容
51         while((dirp=readdir(dp))!= NULL)
52         {
53             if(strcmp(dirp->d_name,".") == 0 ||strcmp(dirp->d_name,"..") == 0)
54                 continue;
55             strcpy(pstr,dirp->d_name);
56            //递归调用
57             showallfile(filepath);
58         }
59     }
60 }

程序测试结果:

输出 /home/anker/Programs目录下面所有的文件。

参考资料:http://linux.die.net/

原文地址:https://www.cnblogs.com/alantu2018/p/8465954.html

时间: 2024-08-14 06:10:29

Unix环境高级编程(二)文件和目录的相关文章

【UNIX环境高级编程】文件 IO 操作 - 基础函数 open close creat lseek write read 详解

博客地址 : http://blog.csdn.net/shulianghan/article/details/46980271 一. 文件打开关闭操作相关函数介绍 1. open 函数 (1) open 函数简介 open 函数解析 : -- 函数定义 : #include <fcntl.h> int open(const char *path, int oflag, ...); -- 函数作用 : 打开或者创建一个文件; -- 返回值 : 打开文件成功, 返回文件描述符; 如果失败, 返回

《unix环境高级编程》 读书笔记 目录

近来读书,做些笔记,来年好翻翻. 本文所使用的操作系统为 CentOS7.0,如果不想装双系统的可以装虚拟机,可以参考这里: http://blog.csdn.net/alex_my/article/details/38142229 当然啦,直接装个再好不过了. 1 链接:http://blog.csdn.net/alex_my/article/details/39079053 涉及主题:文件描述符,系统资源限制,文件相关,close-on-exec, 涉及函数:getrlimit, setrl

Unix环境高级编程(一)文件I/O

Unix系统中大多数文件I/O只需用到五个函数:open.read.write.lseek.close.本章说介绍的I/O是不带缓冲的,即:每个read和write都调用内核中的一个系统调用.不是ISO C的组成部分.对于内核而言,所有打开的文件都通过文件描述符引用. 在<unistd.h>中定义三个标准的文件描述符: STDIN_FILENO 标准输入 STDOUT_FILENO 标准输出 STDERR_FILENO 标准出错输出 具体函数描述:在<fcntl.h>头文件下 in

《Unix环境高级编程》文件I/O

对于内核而言,所有打开的文件都通过文件描述符引用. #include"apue.h"//3-1 测试能否对标准输入设置偏移量 int main(int argc,char *argv[]) { if(lseek(STDIN_FILENO,0,SEEK_CUR) == -1) printf("can't seek"); else printf("seek OK!"); exit(0); }

(十二) 一起学 Unix 环境高级编程 (APUE) 之 进程间通信(IPC)

. . . . . 目录 (一) 一起学 Unix 环境高级编程 (APUE) 之 标准IO (二) 一起学 Unix 环境高级编程 (APUE) 之 文件 IO (三) 一起学 Unix 环境高级编程 (APUE) 之 文件和目录 (四) 一起学 Unix 环境高级编程 (APUE) 之 系统数据文件和信息 (五) 一起学 Unix 环境高级编程 (APUE) 之 进程环境 (六) 一起学 Unix 环境高级编程 (APUE) 之 进程控制 (七) 一起学 Unix 环境高级编程 (APUE)

UNIX环境高级编程笔记之文件I/O

一.看图说话 一图胜过千言,看图! 二.唠一唠 在写之前,先唠几句,<UNIX环境高级编程>,简称APUE,这本书简直是本神书,像我这种小白,基本上每看完一章都是“哇”这种很吃惊的表情.其实大概三年前,那会大三,我就买了这本书,也看过一些,但好像没有留下什么印象,今天再看,依然觉得像新的一样.很大的原因我想是一直以来都在用windows(用windows做开发为什么学不到真正的技术,我想大家都懂的),当然知识结构不完整,学习能力这些就不说了.所以,对于那些致力于想在Linux下做开发的人来说,

《Unix环境高级编程》读书笔记 第3章-文件I/O

1. 引言 Unix系统的大多数文件I/O只需用到5个函数:open.read.write.lseek以及close 本章描述的函数经常被称为不带缓冲的I/O.术语不带缓冲指的是在用户的进程中对其不会自动缓冲,每个read和write都调用内核中的一个系统调用.但是,所有磁盘I/O都要经过内核的块缓存区(也称为内核的缓冲区高速缓存).唯一例外的是对原始磁盘设备的I/O. 2. 文件描述符 对于内核而言,所有打开的文件都通过文件描述符引用.文件描述符是一个非负整数,其变化范围是0~OPEN_MAX

《UNIX环境高级编程》读书笔记 —— 文件 I/O

一.打开或创建一个文件 #include <fcntl.h> int open(const char *pathname, int oflag, .../*mode_t mode*/); 返回值:若成功则返回文件描述符,若出错则返回-1 oflag选项: O_RDONLY O_WRONLY O_RDWR 以上三个常量中必须指定一个,且只能指定一个. 以下常量都是可选的: O_APPED     每次写时追加到文件尾 O_CREAT     若文件不存在,则创建 O_EXCL      若同时指

unix环境高级编程(第三版)中apue.h文件的配置问题

最近刚开始学习unix环境高级编程(第三版),其中有个作者自己写的apue.h文件,在这归总下相应的配置方法,希望对有需要的朋友们有所帮助 首先http://www.apuebook.com/code3e.html 上去下载相应的压缩包,注意自己书的版本. 下载完成之后,鉴于大多数朋友学习linux都是基于虚拟机的,所以顺便附上虚拟机与本地主机传输文件的方式 首先下载SSH Secure Shell 这个工具,然后直接点击quick connect, 弹出如下界面,输入虚拟机的ip地址,和登录用