linux系统编程之文件IO

时间:2023-03-09 02:54:07
linux系统编程之文件IO

1.打开文件的函数open,第一个参数表示文件路径名,第二个为打开标记,第三个为文件权限

linux系统编程之文件IO

linux系统编程之文件IO

代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h> int main()
{
int fd; fd = open("testopen1",O_CREAT,); printf("fd = %d\n",fd); return ; }

效果测试:打印打开文件返回的描述符为3,同时创建了文件testopen1

linux系统编程之文件IO

2.创建文件函数creat和关闭函数close

linux系统编程之文件IO

使用代码

#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
int fd;
if(argc < )
{
printf("please run use ./app filename\n");
exit();
} fd = creat(argv[],); printf("fd = %d\n",fd);
close(fd); return ; }

测试结果:

linux系统编程之文件IO

3.写文件函数write,第一个参数表示要写入的文件的描述符,第二个参数表示要写入的内容的内存首地址,第三个参数表示要写入内容的字节数;

写入成功返回写入的字节数,失败返回-1

linux系统编程之文件IO

linux系统编程之文件IO

测试代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<stdlib.h>
#include<string.h> int main(int argc,char *argv[])
{
int fd;
if(argc < )
{
printf("please run use ./app filename\n");
exit();
} fd = open(argv[],O_CREAT | O_RDWR,); if(fd == -)
{
printf("open file failed!");
exit();
} char *con = "hello world!"; int num = write(fd,con,strlen(con));
printf("write %d byte to %s",num,argv[]); close(fd); return ; }

结果:hello world!写入hello文件成功

linux系统编程之文件IO

查看当前系统最大打开文件个数

linux系统编程之文件IO

4.读取文件read,第一个参数是文件描述符,第二个参数是存储读取文件内容的内存首地址,第三个参数是一次读取的字节数

linux系统编程之文件IO

测试代码,完成文件复制

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<stdlib.h>
#include<string.h> int main(int argc,char *argv[])
{
int fd_src,fd_des;
char buf[]; if(argc < )
{
printf("please run use ./app srcfilename desfilename\n");
exit();
} fd_src = open(argv[],O_RDONLY);
fd_des = open(argv[],O_CREAT | O_WRONLY | O_TRUNC,); if(fd_src != - && fd_des != -)
{
int len = ;
while(len = read(fd_src,buf,sizeof(buf)))
{
write(fd_des,buf,len);
} close(fd_src);
close(fd_des);
} return ; }

效果查看,可见实现了文件open.c的拷贝

linux系统编程之文件IO