操作系统.系统文件IO
系统调用:(系统API)
系统调用就是操作系统提供的一些功能给程序员调用,这些系统调用被封装成C函数的形式提供给程序员,
但是它们不是函数且不是标准C中的一部分
一般应用程序运行在用户态(0~3G)上,当使用系统调用时运行在内核态(3~4G)
常用的标准库函数大部分时间工作在用户态,底层偶尔会调用系统调用进入内核态,结束调用后会转会用户态
系统调用的代码是内核的一部分,其外部借口以函数形式定义在共享库中(linux-gate.so、ld-linux.so),这些接口的实现
利用软中断进入内核态进行真正的系统调用
real 0m0.009s 总执行时间
user 0m0.005s 用户态总用时
sys 0m0.005s 内核态总用时
real=用户态+内核态+切换时间
一切皆文件:
UNIX/Linux系统把所有的服务、设备等一切内容都抽象成了文件、并提供了一套简单而统一的接口,
这部分接口就是系统文件读写调用、简称系统IO
标准C库提供的文件读写函数称为标准IO
也就说在UNIX/Linux系统中任何对象都可以被当作文件看待,可以以文件形式访问
文件的分类:
普通文件 - 包含二进制、文本、压缩、库文件
目录文件 d 有执行权限才能访问
块设备文件 b 保存大块数据的设备,例如硬盘
字符设备文件 c 存储与字符相关的设备文件,例如键盘、鼠标等设备
管道文件 p 与进程间通信相关文件
Socket文件 s 链接文件
文件相关的系统调用
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
功能:打开文件
pathname:打开文件的路径
flags:打开文件的方式
O_RDONLY 只读
O_WRONLY 只写
O_RDWR 读写
O_CREAT 文件不存在则创建 需要加入mode参数
O_APPEND 追加在末尾
O_EXCL 如果文件存在则创建失败
O_TRUNC 如果文件存在则清空打开
返回值:文件描述符 0以上的整数 也是表示一个打开的文件的凭证
int open(const char *pathname, int flags, mode_t mode);
功能:打开文件
pathname:打开文件的路径
flags:打开文件的方式 有O_CREAT
mode: 文件权限 0644
S_IRWXU 00700 拥有者 读写执行权限
S_IRUSR 00400 读权限
S_IWUSR 00200 写权限
S_IXUSR 00100 执行权限
S_IRWXG 00070 同组 读写执行权限
S_IRGRP 00040 读权限
S_IWGRP 00020 写权限
S_IXGRP 00010 执行权限
S_IRWXO 00007 其他 读写执行权限
S_IROTH 00004 读
S_IWOTH 00002 写
S_IXOTH 00001 执行
返回值:文件描述符
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc,const char* argv[])
{
//int fd = open("test.txt",O_RDWR|O_CREAT|O_EXCL,0644);
int fd = open("test1.txt",O_WRONLY);
if(0 > fd)
{
perror("open");
return -1;
}
printf("打开文件成功!\n");
}
int creat(const char *pathname, mode_t mode);
功能:创建文件
mode:等同于open的mode
返回值:文件描述符
strace ./a.out 追踪程序的底层调用
#include <unistd.h>
ssize_t write(int fd,const void *buf,size_t count)
功能:把内存中的数据写入到文件中
fd:文件描述符 open的返回值
buf:待写入数据的内存首地址
count:要写入的字节数
返回值:成功写入的字节数
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,const char* argv[])
{
int fd = open("test.txt",O_RDWR|O_CREAT|O_TRUNC,0644);
if(0 > fd)
{
perror("open");
return -1;
}
char* str = "hehehahaxixi";
int ret = write(fd,str,strlen(str)+1);
/*
for(int i=0; i<10; i++)
{
int ret = write(fd,&i,sizeof(i));
printf("ret=%d\n",ret);
}
*/
char buf[256] = {};
ret = read(fd,buf,sizeof(buf));
printf("%d %s\n",ret,buf);
close(fd);
}
ssize_t read(int fd, void *buf, size_t count);
功能:从文件中读取数据到内存
fd:文件描述符
buf:存储数据的内存首地址
count:要读取的字节数
返回值:实际读取到的字节数
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,const char* argv[])
{
int fd = open("test.txt",O_RDONLY);
if(0 > fd)
{
perror("open");
return -1;
}
// char buf[256] = {};
// int ret = read(fd,buf,sizeof(buf));
int num = 0;
for(int i=0; i<10; i++)
{
int ret = read(fd,&num,sizeof(num));
printf("ret=%d ",ret);
printf("num:%d\n",num);
}
}
int close(int fd);
功能:关闭一个文件
返回值:成功返回0 失败返回-1
练习1:
分别使用标准IO(fwrite)和系统IO(write)写入一百万个随机数整数到文件中,测试他们谁更快,为什么?
结论:使用标准IO比直接使用系统IO更快,原因是标准IO有缓冲区机制,在写入数据时并不是立即直接调用系统IO进行写入,
而是先把缓冲区写慢后,再调用系统调用写入到文件中而直接使用系统IO会反复地切换用户态和内核态,更加耗时,
但是当我们给系统IO增加一个大的缓冲区时,它的速度要比标准IO更快
标准IO > 系统IO
系统IO+缓冲区 > 标准IO
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
void std_io(void)
{
FILE* fwp = fopen("test.txt","w");
if(NULL == fwp)
{
perror("fopen");
return;
}
for(int i=0; i<1000000; i++)
{
int num = rand();
fwrite(&num,sizeof(num),1,fwp);
}
fclose(fwp);
}
void sys_io(void)
{
int fd = open("test.txt",O_WRONLY|O_CREAT|O_TRUNC,0644);
if(0 > fd)
{
perror("open");
return;
}
int arr[8192] = {};
for(int i=0; i<1000000; i++)
{
arr[i%8192]= rand();
if(0 == (i+1)%8192)
{
write(fd,arr,sizeof(arr));
}
}
close(fd);
}
int main(int argc,const char* argv[])
{
std_io();
//sys_io();
}
练习2:
使用系统IO实现一个带覆盖检测的cp命令
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <getch.h>
int main(int argc,const char* argv[])
{
if(3 != argc)
{
printf("User:./Cp src dest\n");
return 0;
}
int src = open(argv[1],O_RDONLY);
if(0 > src)
{
printf("源文件不存在,请检查!\n");
return 0;
}
int dest = open(argv[2],O_WRONLY|O_CREAT|O_EXCL,0644);
if(0 > dest)
{
printf("目标文件已存在,是否覆盖(y/n)\n");
char cmd = getch();
printf("%c\n",cmd);
if('y' != cmd && 'Y' != cmd)
{
printf("停止拷贝\n");
close(src);
return 0;
}
else
{
printf("进行覆盖!\n");
dest = open(argv[2],O_WRONLY|O_TRUNC);
}
}
int ret = 0;
char buf[4096] = {};
while(ret = read(src,buf,sizeof(buf)))
{
write(dest,buf,ret);
}
close(src);
close(dest);
}
随机读写:
每个打开的文件都有一个记录读写位置的指针,叫做文件位置指针,所有对文件的读写操作都是从该指针的位置进行的,
该指针会随着文件的读写自动往后移动
当需要调整读写位置时,通过fseek\lseek进行调整
off_t lseek(int fd, off_t offset, int whence);
fd:文件描述符
offset:偏移值
whence:基础位置
SEEK_SET 开头
SEEK_CUR 当前
SEEK_END 结尾
返回值:成功返回调整后位置指针的位置,失败返回-1
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int file_size(const char* path)
{
int fd = open(path,O_RDONLY);
if(0 > fd)
{
perror("open");
return -1;
}
int size = lseek(fd,0,SEEK_END);
close(fd);
return size;
}
int main(int argc,const char* argv[])
{
//printf("%d\n",file_size("test.txt"));
int fd = open("test.txt",O_RDWR);
lseek(fd,4,SEEK_END);
char* str = "qqqqq";
write(fd,str,strlen(str)+1);
close(fd);
}
注意:在越过文件末尾的位置写入数据,则原末尾与数据之间形成"空洞",空洞会计算入文件大小,但不占用磁盘空间
系统IO的文本文件读写:
系统IO没有类似fprintf\fscanf函数,因此不能直接以文本形式读写文本文件,可以间接通过sprintf\sscanf读写
写文本文件:
先把各种类型数据内容通过 sprintf 转换成字符串,然后再通过write写入文件
读取文本文件:
先按照字符串形式读到内存中,然后通过sscanf转换成对应的各种类型数据
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
typedef struct Student
{
char name[20];
char sex;
short age;
int id;
}Student;
int main(int argc,const char* argv[])
{
int fd = open("stu.txt",O_RDWR);
printf("fd:%d\n",fd);
int fd1 = open("test.txt",O_RDWR);
printf("fd:%d\n",fd1);
if(0 > fd)
{
perror("open");
return -1;
}
/*
Student stu = {"张三",'w',20,1001};
for(int i=0; i<10; i++)
{
char buf[256] = {};
stu.id += 1;
stu.age += 2;
sprintf(buf,"%s %c %hd %d\n",stu.name,stu.sex,stu.age,stu.id);
write(fd,buf,strlen(buf));
}
close(fd);
*/
char* buf = malloc(4096);
char* temp = buf;
read(fd,buf,4096);
while(strstr(buf,"\n"))
{
Student stu = {};
sscanf(buf,"%s %c %hd %d\n",stu.name,&stu.sex,&stu.age,&stu.id);
printf("read:%s %c %hd %d\n",stu.name,stu.sex,stu.age,stu.id);
buf = strstr(buf,"\n")+1;
}
free(temp);
close(fd);
}
文件描述符:
1、非负整数,代表打开的文件
2、通过系统调用open\creat返回,可以被内核引用
3、它代表了一个内核对象,因为内核不能暴露它的内存地址,不能返回真正的内核对象的地址,只能用文件描述符来对应
4、内核中有一张打开文件的表格,文件描述符是访问这张表的下标,因此也称为"句柄",相当于访问已打开文件的凭证
内核中有三个默认一直打开的文件描述符
0 标准输入文件 对应打开的文件指针 stdin scanf底层往里面读
1 标准输出文件 对应打开的文件指针 stdout printf底层往里面写
2 标准错误文件 对应打开的文件指针 stderr
文件描述符的复制:
int dup(int oldfd);
功能:复制一个已打开的文件描述符
返回值:返回一个当前没有使用过的最小的文件描述符
int dup2(int oldfd, int newfd);
功能:复制成一个指定的文件描述符
返回值:成功返回newfd,失败返回-1
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,const char* argv[])
{
int fd = open("test.txt",O_RDWR|O_TRUNC);
if(0 > fd)
{
perror("open");
return -1;
}
int newfd = dup(fd);
char* str = "xixi";
write(newfd,str,4);
lseek(fd,8,SEEK_SET);
write(newfd,str,4);
close(fd);
close(newfd);
write(fd,str,4);
}
注意:复制成功后,相当与两个不同值的文件描述符对应同一个已打开的文件,并且打开方式都一样
注意:其中一个文件描述符关闭,不影响复制出来的文件描述符,但是他们共享同一个文件位置指针