#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main()
{
int rfd = open("text.txt", O_RDWR | O_CREAT, 0775);
int wfd = open("text2.txt", O_RDWR | O_CREAT, 0775);
if (rfd == -1 || wfd == -1)
{
perror("打开文件错误");
exit(1);
}
while (true)
{
char str[1024] = {'\0'};
printf("请输入数据\n");
scanf("%s", str);
int res = write(rfd, str, sizeof(str) / sizeof(str[0]));
if (res == -1)
{
perror("写入文件错误");
break;
}
// 重新定位文件指针到文件开头
if (lseek(rfd, 0, SEEK_SET) == -1)
{
perror("定位文件指针错误");
break;
}
char rstr[1024] = {'\0'};
int n;
while (n = read(rfd, rstr, 1024))
{
if (n == -1)
{
perror("读取错误");
break;
}
printf("%s\n", rstr);
res = write(wfd, rstr, n);
if (res == -1)
{
perror("写入文件错误");
break;
}
}
if (n == -1)
{
perror("读取错误");
break;
}
memset(rstr, 0, 1024);
}
close(rfd);
close(wfd);
return 0;
}
Linux的文件读写操作
最新推荐文章于 2024-09-02 13:58:52 发布