C语言文件操作示例:拼接两个文件内容
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h>
#define PATH1 '1.txt' #define PATH2 '2.txt' #define PATH3 '3.txt'
int main(int argc, char const *argv[]) { int fd1 = open(PATH1, O_RDWR | O_CREAT, 0777); //创建并打开1.txt if (fd1 == -1) { printf("open %s failed\n", PATH1); exit(-1); }
int fd2 = open(PATH2, O_RDWR | O_CREAT, 0777); //创建并打开1.txt
if (fd2 == -1)
{
printf("open %s failed\n", PATH2);
exit(-1);
}
int fd3 = open(PATH3, O_RDWR | O_CREAT, 0777);
if (fd3 == -1)
{
printf("open %s failed\n", PATH3);
exit(-1);
}
char buf1[100];
printf("请输入hello: ");
scanf("%s", buf1);
write(fd1, buf1, strlen(buf1)); // 将用户输入的hello写入到fd1
char buf2[100];
printf("请输入world: ");
scanf("%s", buf2);
write(fd2, buf2, strlen(buf2)); // 将用户输入的world写入到fd2
lseek(fd1, 0, SEEK_SET); // 将fd1的文件指针移到文件开头
lseek(fd2, 0, SEEK_SET); // 将fd2的文件指针移到文件开头
char buf3[100];
bzero(buf3, sizeof(buf3)); // 清空buf3
int read_return = read(fd1, buf3, sizeof(buf3) - 1); // 从fd1读取内容到buf3
if (read_return == -1)
{
printf("read %s failed\n", PATH1);
exit(-1);
}
read_return = read(fd2, buf3 + strlen(buf3), sizeof(buf3) - strlen(buf3) - 1); // 从fd2读取内容追加到buf3
if (read_return == -1)
{
printf("read %s failed\n", PATH2);
exit(-1);
}
printf("拼接后的内容: %s\n", buf3);
write(fd3, buf3, strlen(buf3)); // 将拼接后的内容写入fd3
close(fd1);
close(fd2);
close(fd3);
return 0;
}
read_return = read(fd2, buf3 + strlen(buf3), sizeof(buf3) - strlen(buf3) - 1); // 从fd2读取内容追加到buf3 这段代码中为什么要加
内容:read_return = read(fd2, buf3 + strlen(buf3), sizeof(buf3) - strlen(buf3) - 1); // 从fd2读取内容追加到buf3
这段代码的作用是从文件描述符fd2中读取内容,并将读取的内容追加到buf3的末尾。
strlen(buf3)表示buf3当前已经存储的字符串的长度,buf3 + strlen(buf3)表示从buf3字符串的末尾位置开始存储读取的内容。
sizeof(buf3) - strlen(buf3) - 1表示从buf3末尾位置开始,还能存储的剩余空间大小。
因此,这段代码的目的是将fd2中的内容追加到buf3中,以实现将两个文件的内容拼接在一起。
原文地址: https://www.cveoy.top/t/topic/qj9J 著作权归作者所有。请勿转载和采集!