本章主要介绍的是文件结构及目录。重点是通过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/

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

  1. 【UNIX环境高级编程】文件I/O

    [UNIX环境高级编程]文件I/O大多数文件I/O只需要5个函数: open.read.write.lseek以及close 不带缓冲的I/O: 每个read和write都调用内核中的一个系统调用 1 ...

  2. Unix环境高级编程:文件 IO 原子性 与 状态 共享

    参考 UnixUnix环境高级编程 第三章 文件IO 偏移共享 单进程单文件描述符 在只有一个进程时,打开一个文件,对该文件描述符进行写入操作后,后续的写入操作会在原来偏移的基础上进行,这样就可以实现 ...

  3. 【UNIX环境高级编程】文件 IO 操作 一 ( open | close | creat | lseek | write | read )

    博客地址 : http://blog.csdn.net/shulianghan/article/details/46980271 一. 文件打开关闭操作相关函数介绍 1. open 函数 (1) op ...

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

    Unix系统中大多数文件I/O只需用到五个函数:open.read.write.lseek.close.本章说介绍的I/O是不带缓冲的,即:每个read和write都调用内核中的一个系统调用.不是IS ...

  5. Unix环境高级编程(二十)伪终端

    1.综述 伪终端对于一个应用程序而言,看上去像一个终端,但事实上伪终端并不是一个真正的终端.从内核角度看,伪终端看起来像一个双向管道,而事实上Solaris的伪终端就是用STREAMS构建的.伪终端总 ...

  6. Unix环境高级编程(二十一)数据库函数库

    本章的内容是开发一个简单的.多用户数据库的C函数库.调用此函数库提供的C语言函数,其他程序可以读取和存储数据库中的记录.绝大部分商用数据库函数库提供多进程同时更新数据库所需要的并发控制,采用建议记录锁 ...

  7. [置顶] 文件和目录(二)--unix环境高级编程读书笔记

    在linux中,文件的相关信息都记录在stat这个结构体中,文件长度是记录在stat的st_size成员中.对于普通文件,其长度可以为0,目录的长度一般为1024的倍数,这与linux文件系统中blo ...

  8. (二) 一起学 Unix 环境高级编程 (APUE) 之 文件 IO

    . . . . . 目录 (一) 一起学 Unix 环境高级编程 (APUE) 之 标准IO (二) 一起学 Unix 环境高级编程 (APUE) 之 文件 IO (三) 一起学 Unix 环境高级编 ...

  9. (三) 一起学 Unix 环境高级编程 (APUE) 之 文件和目录

    . . . . . 目录 (一) 一起学 Unix 环境高级编程 (APUE) 之 标准IO (二) 一起学 Unix 环境高级编程 (APUE) 之 文件 IO (三) 一起学 Unix 环境高级编 ...

随机推荐

  1. android 多线程概述

    android多线程,一直是一个麻烦的事情,要掌握它的本质,我们需要搞清楚一个问题,linux多线程的本质. 我们这篇文章,来讨论以下的议程: 了解linux的历程,了解android的异步任务机制, ...

  2. Jmeter-Maven-Plugin高级应用:Modifying Properties

    Modifying Properties Pages 12 Home Adding additional libraries to the classpath Advanced Configurati ...

  3. 单页WEB应用(三),Chat聊天模块

    Chat 聊天模块 这个模块应该就是该书全篇的唯一一个模块吧,后面差点儿全部的篇章都环绕这个模块去实现的,只是就通过这一个模块的实现和上线,也能体现单页应用开发到公布上线的整个过程,毕竟后面的数据.通 ...

  4. The 6 inspectors in XCode

    Name Shortcut Key Description file helper Command + Option + 1 shows you all the file details relate ...

  5. 提高ASP.NET首页性能的十大方法

    本文是我对ASP.NET页面载入速度提高的一些做法,这些做法分为以下部分: http://www.cnblogs.com/xiachufeng/archive/2011/11/09/2242130.h ...

  6. HDU1588-Gauss Fibonacci(矩阵高速幂+等比数列二分求和)

    题目链接 题意:g(x) = k * x + b.f(x) 为Fibonacci数列.求f(g(x)),从x = 1到n的数字之和sum.并对m取模. 思路:  设A = |(1, 1),(1, 0) ...

  7. Hibernate日期映射类型

    映 射 类 型 Java类型 标准SQL类型 描    述 date java.util.Date或者java.sql.Date DATE 代表日期,形式为: YYYY-MM-DD time java ...

  8. Java类(继承)初始化顺序

    /** * Created by xfyou on 2016/11/2. * Java继承的初始化 */ public class Beetle extends Insect { int k = pr ...

  9. UIkit – 轻量级前端框架

    原始地址:UIkit – 轻量级前端框架 高效轻量级前端框架: 来自:咕噜分享

  10. 错误:google-chrome-stable-44.0.2403.157-1.x86_64.rpm 的公钥没有安装

    错误:google-chrome-stable-44.0.2403.157-1.x86_64.rpm 的公钥没有安装 Fedora22 系统更新软件包.出现: warning: /var/cache/ ...