C中的文件I/O主要就是有几个函数需要我们需要知道了解,有open函数,read函数,write函数,以及close函数。
open函数的使用
open:
打开一个文件
NAME
open, openat, creat - open and possibly create a file
SYNOPSIS
#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 可读可写
返回值:成功返回一个新的文件描述符
失败返回-1,同时error被设置
close函数的使用
close:
关闭一个文件
NAME
close - close a file descriptor
SYNOPSIS
#include <unistd.h>
int close(int fd);
fd:文件描述符,我们打开的那个文件
read函数的使用
read:
从文件中读取内容
NAME
read - read from a file descriptor
SYNOPSIS
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
fd:文件描述符,我们打开的那个文件
buf:我们将读到的内容存放的地方
count:读多少字节
返回值:成功返回读到的字节数(返回0时代表文件读完)
失败返回-1,同时error被设置
write函数的使用
write:
向文件中写入内容
NAME
write - write to a file descriptor
SYNOPSIS
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
fd:文件描述符,我们打开的那个文件
buf: 我们要写入的内容
count: 写多少字节
返回值:成功返回写入的字节数(返回0,代表没有写进去)
失败返回-1,同时error被设置
当我们使用系统文件的时候,就是要注意使用那几个规定的头文件的,通过使用头文件里面的函数来完成我们想要的功能。
练习:
通过系统函数的调用完成将一个函数里面的东西,写到另一个函数里面去。
#include <sys/types.h>
#include <sys/stat.h>
#include<stdio.h>
#include <fcntl.h>
int main()
{
int fd = open("nice.c",O_RDWR);
int fd2=open("cp1.c",O_RDWR);
char buf[5000]={0};//这里其实是有一个缺陷的,这样做太浪费空间了。
while(1)
{
int read1;
read1= read(fd,buf,1);
write(fd2,buf,1);
if(read1==0)
{
close(fd2);
close(fd);
break;
}
}
return 0;
}
最后,做一下总结吧,就是其实通过系统I/O来操作文件其实就是操作fd文件操作符。