操作系统API:API是一些函数,这些函数是由linux系统提供支持的,由应用层程序来使用。应用层程序通过调用API来调用操作系统中的个各种功能来干活。
学习一个操作系统,其实就是学习使用这个操作系统的API
linux常用文件IO接口:open close write read lseek
文件操作的一般步骤:先open打开一个文件,得到一个文件描述符,然后对文件进行读写,最后close文件
文件平时是存放在块设备的文件系统中的,我们把这种文件叫静态文件。当我们open一个文件时,linux内核:在进程中建立一个打开文件的数据结构,记录下我们打开的文件,内核在内存中申请一段内存,并且将静态文件的内容从块设备中读取到内存中特定地址管理存放(动态文件)
打开文件后,以后对这个文件的读写操作,都是针对内存中的动态文件的,而并不是针对静态文件的,当我们对动态文件记性读写时,内存中的动态文件和块设备中的静态文件就不同步了,当我们close关闭动态文件时,close内部内核将内存中的动态文件的内容去同步块设备中的静态文件
文件描述符实质上是一个数字,这个数字在一个进程中表示一个特定的含义,当我们open打开一个文件时,操作系统在内存中构建了一些数据结构来表示这个动态文件,然后返回给应用程序一个数字作为文件描述符,这个数字就和我们内存中维护这个动态文件的这些数据结构挂钩绑定上了,以后我们应用程序如果操作这个动态文件,只需要用这个文件描述符进行区分
文件描述符就是用来区分一个程序打开的多个文件的。作用域就是当前进程,出了进程文件描述符就没有意义了。
man 1 查shell命令 man 2 查API,man 3 查库函数
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
int fd = -1; //fd为文件描述符
//打开文件
fd = open("a.txt",O_RDWR);
if(-1 == fd)
{
printf("文件打开错误\n");
}
else
{
printf("文件打开成功 fd = %d\n",fd);
}
//读写文件
//关闭文件
close(fd);
return 0;
}
读写
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
int fd = -1; //fd为文件描述符
char buf[100] = {0};//缓冲区
char writebuf[20]="linux";
int ret = -1;
//打开文件
fd = open("a.txt",O_RDWR);
if(-1 == fd)
{
printf("文件打开错误\n");
}
else
{
printf("文件打开成功 fd = %d\n",fd);
}
//读文件
ret = read(fd,buf,20);
if(ret <0)
{
printf("read 读取失败\n");
}
else
{
printf("读取了%d\n",ret);
printf("文件内容是%s\n",buf);
}
//关闭文件
close(fd);
return 0;
}
写文件
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>
#include<string.h>
int main(int argc,char *argv[])
{
int fd = -1; //fd为文件描述符
//打开文件
fd = open("a.txt",O_RDWR);
if(-1 == fd)
{
printf("文件打开错误\n");
}
else
{
printf("文件打开成功 fd = %d\n",fd);
}
//写文件
ret = write(fd,writebuf,strlen(writebuf));
if(ret <0)
{
printf("读取失败 \n");
}
else
{
printf("write %d\n",ret);
}
//关闭文件
close(fd);
return 0;
}
6