一、文件IO
(一)文件IO 基本概要
1、概念
- 标准IO是有缓存的IO,文件IO没有缓存,适合于通信、硬件设备操作
- 标准IO是库函数,文件IO是系统调用
2、系统调用和库函数
- 系统调用:是Linux内核中的代码,只能在Linux系统中使用
- 库函数:是对系统调用的封装,可以在不同的操作系统中安装并使用,库函数最终还是要调用系统调用完成对应功能
3、基本文件IO函数接口
| 标准IO | 文件IO |
| fopen | open |
| fclose | close |
| fgetc/fputc | read/write |
| fgets/fputs |
.... |
| fscanf/fprintf | .... |
| fread/fwrite | .... |
| fseek/ftell/rewind | lseek |
(二)基本文件IO函数接口
1、open:文件打开

2、close:文件关闭

3、标准IO对应的文件IO的打开方式

4、read:读
5、write:写

6、文件描述符偏移量的定位 lseek

7. 文件IO与标准IO互相转换的函数
1) fileno
功能:根据文件流指针获得文件描述符
2) fdopen
功能:根据已经打开的文件描述符获得文件流指针
3) feof
功能:判断文件流指针是否到达末尾
4)ferror
功能:判断文件流指针是否出错
- 示例:
1、使用lseek实现文件描述符偏移量的定位
头文件写的多了,可以集成在一个文件里,用的时候调用这个文件即可
#ifndef __HEAD_H__
#define __HEAD_H__#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <math.h>
#include <dirent.h>#endif
代码实现
#include "../head.h"
int main(void)
{
FILE ;
int fd = 0;
char ch = 0;
off_t len = 0;fd = open("a.txt", O_WRONLY | O_CREAT, 0664);
if (-1 == fd)
{
perror("fail to open");
return -1;
}len = lseek(fd, 10, SEEK_SET);
printf("偏移量:%ld\n", len);
ch = 'a';
write(fd, &ch, 1);
len = lseek(fd, 0, SEEK_CUR);
printf("偏移量:%ld\n", len);len = lseek(fd, -5, SEEK_CUR);
printf("偏移量:%ld\n", len);
ch = 'b';
write(fd, &ch, 1);
len = lseek(fd, 0, SEEK_SET);
printf("偏移量:%ld\n", len);
ch = 'c';
write(fd, &ch, 1);close(fd);
return 0;
}
2、使用read和write实现文件拷贝
文件IO的read和write可以实现文件拷贝,包括普通ASCII还有二进制文件(图片)
代码实现

拷贝文本结果



拷贝图片结果


二、目录IO
(一) 目录IO 基本概要
1、操作方式:
- 打开目录文件
- 读取目录文件中的目录项
- 关闭目录文件
(二) 目录IO 函数接口


8.文件名和路径:
1)file.txt:文件名
2)./file.txt:路径
- 示例
打印当前目录的文件属性


三、时间相关的函数接口
1、时间类型分类
1) time_t 类型时间
1970-1-1到现在的秒数
一般用于时间计算相关逻辑
2) struct tm 类型时间
包含年月日时分秒信息
3) char *字符串类型时间
由时间拼接的字
2、函数接口



5.示例




被折叠的 条评论
为什么被折叠?



