文件IO的概念
什么是文件IO:文件IO又称系统IO,系统调用,是操作系统提供的API接口函数。
POSIX接口(了解)
注意:文件IO不提供缓冲机制
文件IO的API :open close read write
文件IO的打开使用
文件描述符概念:
英文:缩写 fd (file descriptor)
是0-1023的数字,表示文件。
0,表示标准输入;
1.表示标准输出;
2,表示出错;
文件IO打开
int open(const char *pathname, int flags); //不创建文件
int open(const char *pathname, int flages, mode_t mode);//创建文件,不能创建设备文件成功时
//返回文件描述符,出错时返回EOF
文件IO和标准的模式对应关系
r | O_RDONLY |
r+ | O_RDWR |
w | O_WRONLY | O_CREAT | O_TRUNC, 0664 |
w+ | O_RDWR | O_CREAT | O_TRUNC, 0664 |
a | O_WRONLY | O_CREAT | O_APPEND, 0664 |
a+ | O_RDWR | O_CREAT | O_APPEND, 0664 |
umask概念
umask用来设定文件或目录的初始权限
文件IO的关闭
int close (int fd);
关闭后文件描述符不能代表文件;
文件IO的读写和定位
1、文件IO-read
read函数用来从文件中读取数据:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);//(文件描述符,缓冲区,读多少数据)
成功时返回实际读取的字节数;出错时返回EOF
读到文件末尾时返回0
buf是接收数据的缓冲区
count不应超过buf大小
2、文件IO-write
write函数用来向文件写入数据:
#include <unistd.h>
ssize_t write(int fd, void *buf, size_t count);
成功时返回实际写入的字节数;出错时返回EOF
buf是发送数据的缓冲区
count不应超过buf大小
容易出错点:
求字符串长度应使用strlen,对二进制数据使用sizeof(strlen遇见\0就结束)
printf 的字符应添加’\0’
3、文件IO-lseek
lseek函数用来定位文件:
#include <unistd.h>
off_t lseek(int fd, off_t offset, intt whence); //(要定位的文件,偏移量,从哪儿偏移)
成功时返回当前的文件读写位置;出错时返回EOF
参数offset和参数whence同fseek完全一样
使用文件IO实现
“每隔1秒向文件1.txt写入当前系统时间,行号递增”
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
int fd;
time_t ctime;
struct tm *ctimestr;
int ret;
int linecount = 0;
char buf[100];
fd = open("time.txt", O_RDWR | O_CREAT | O_APPEND, 0666);
if (fd < 0) {
perror("open");
return 0;
}
while(read(fd, buf, strlen(buf)) != 0) {
if (buf[strlen(buf)-1] == '\n') {
linecount++;
}
}
while (1) {
ctime = time(NULL);
ctimestr = localtime(&ctime);
printf("%d, %04d-%02d-%02d %02d:%02d:%02d\n", linecount, ctimestr->tm_year+1900, ctimestr->tm_mon+1, ctimestr->tm_mday,
ctimestr->tm_hour, ctimestr->tm_min, ctimestr->tm_sec);
sprintf(buf, "%d, %04d-%02d-%02d %02d:%02d:%02d\n", linecount, ctimestr->tm_year+1900, ctimestr->tm_mon+1, ctimestr->tm_mday,
ctimestr->tm_hour, ctimestr->tm_min, ctimestr->tm_sec);
ret = write(fd, buf, strlen(buf));
if (ret < 0) {
perror("write");
goto end;
}
lseek(fd, 0, SEEK_SET);
linecount++;
sleep(1);
}
end:
close(fd);
}