《APUE》读书笔记—第四章文件和目录

本文介绍了如何使用stat系列函数获取Unix文件的详细信息,并通过示例程序展示了如何遍历目录和输出目录下的文件详情。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第四章主要介绍的是文件结构及目录。重点是通过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 fileFIFO套接字,符号链接(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 */
};

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

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <errno.h>
void ShowAllFile(char* FilePath);
int main(int argc, char* argv[])
{
	if (argc != 2)
	{
		//需要输入两个参数
		printf("Error! Please input FilePath.\n");
		exit(-1);//
	}
    //argv[1]中是目录参数
    ShowAllFile(argv[1]);
    return 0;
}
void ShowAllFile(char* FilePath)
{
	struct stat st;
	DIR * dp;
	struct dirent* dirp;
	char *pstr;
	//进行文件信息的获取
	if (lstat(FilePath, &st) == -1)
	{
		perror("lstat() error");
		exit(-1);
		//判断文件是否是目录文件
		if (S_ISDIR(st.st_mode) == 0)//显然不是
		{
			printf("File:%s\n", FilePath);
		}
		else
		{
			printf("Directory: %s\n", FilePath);
			pstr = FilePath + strlen(FilePath);
			*pstr++ = '/';
			*pstr = 0;
			//打开目录
			if (dp = opendir(FilePath) == NULL)
			{
				printf ("opendir() error");
				exit(-1);
			}
			//读取该目录下的内容
			while ((dirp = readdir(dp)) != NULL)
			{
				//读到该目录和上层目录
				if (strcmp(dirp->d_name, ".") == 0) || (strcmp(dirp->d_name, "..") == 0)
					continue;
				strcpy(pstr, dirp->d_name);
				//递归调用
                ShowAllFile(FilePath);
			}
		}
	}
}

程序测试结果如下:


### APUE 第三章 学习笔记 #### 文件 I/O 基础 APUE 的第三章主要讨论了 Unix 系统中的文件 I/O 操作基础。这一章节涵盖了多个重要的概念技术细节,对于理解如何高效地操作文件至关重要。 #### 打开关闭文件 为了打开一个文件,程序通常会使用 `open` 或者 `creat` 函数[^1]。这两个函数都返回一个小于零的整数作为错误指示,而成功的调用则返回一个非负整数表示新创建的文件描述符。当不再需要访问某个特定文件时,应该通过调用 `close` 来关闭它。这不仅释放了与该文件关联的操作系统资源,而且也使得这个文件描述符能够被重新利用。 ```c #include <fcntl.h> /* For O_* constants */ #include <unistd.h> /* For open(), close() */ int fd; fd = open("example.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (fd >= 0) { // File opened successfully. } // Later... close(fd); ``` #### 文件读写 一旦有了有效的文件描述符,就可以对其进行读取 (`read`) 写入 (`write`) 操作。这些基本的 I/O 操作允许应用程序直接处理底层的数据流而不必关心具体的设备特性[^2]。 ```c char buffer[BUFSIZ]; ssize_t n; n = read(fd, buffer, BUFSIZ - 1); if (n > 0) { buffer[n] = '\0'; // Null terminate the string printf("%s\n", buffer); } const char *msg = "Hello world!"; write(fd, msg, strlen(msg)); ``` #### 文件定位 除了简单的顺序读写外,还可以改变当前文件偏移量来实现随机访问。这是通过 `lseek` 实现的功能之一,它可以向前或向后移动文件指针的位置以便从不同的位置开始读写数据[^3]。 ```c off_t offset; offset = lseek(fd, SEEK_SET, 0); // Move to beginning of file if (offset != -1L) { // Seek succeeded. } ``` #### 特殊文件类型的支持 Unix 系统支持多种特殊类型的文件对象,比如管道、套接字以及终端设备等。本章还介绍了针对这些不同类型文件的具体 API 接口支持机制[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值