读文件:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //linux下面的头文件
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main(int avg, char* avgs[])
{
if (avg < 2)
{
printf("参数错误\n");
return EXIT_FAILURE;
}
char s[] = "abc.txt";
int fd = open(avgs[1], O_RDONLY);
if (fd == -1)
{
printf("error :%s\n", strerror(errno));
}
else
{
printf("fd=%d\n", fd);
char buf[100];
memset(buf, 0, sizeof(buf));
//循环读取文件
while (read(fd, buf, sizeof(buf)-1)>0)
{
printf("buf:%s\n", buf);
memset(buf, 0, sizeof(buf));
}
close(fd);
}
return 0;
}
写文件:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //linux下面的头文件
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main(int avg, char* avgs[])
{
if (avg < 2)
{
printf("参数错误\n");
return EXIT_FAILURE;
}
int fd = open(avgs[1], O_RDWR | O_APPEND);
if (fd==-1)
{
printf("file open error : %s \n", strerror(errno));
return EXIT_FAILURE;
}
else
{
printf("fd= %d\n", fd);
char buf[100];
memset(buf, 0, sizeof(buf));
strcpy(buf, "RtesttesttestR");
int i = write(fd, buf, strlen(buf));
close(fd);
}
return 0;
}

原文:https://www.cnblogs.com/caoruipeng/p/11826817.html