这段代码演示了如何使用C语言的系统调用函数打开、读写文件,并将多个文件的内容合并到一个新的文件中。

代码首先使用 open() 函数打开三个文件 1.txt2.txt3.txt,并使用 O_RDWR | O_CREAT 标志以读写模式创建文件,若文件不存在则创建。

然后,代码提示用户输入两个字符串,分别写入到 1.txt2.txt 文件中。

接着,使用 lseek() 函数将文件指针移动到文件开头,以便从文件开头读取内容。

代码使用 read() 函数从 1.txt 文件中读取内容到 buf3 缓冲区中。然后,再次使用 read() 函数从 2.txt 文件中读取内容,并追加到 buf3 缓冲区中。需要注意的是,read() 函数的第二个参数是 buf3 + strlen(buf3),表示从 buf3 缓冲区的末尾位置开始写入数据。第三个参数 sizeof(buf3) - strlen(buf3) - 1 表示剩余的缓冲区空间大小,确保读取的内容不会超过缓冲区的容量。

最后,代码使用 write() 函数将 buf3 缓冲区中的内容写入到 3.txt 文件中。

#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 中。
  • buf3 + strlen(buf3) 表示从 buf3 的末尾位置开始追加内容。
  • sizeof(buf3) - strlen(buf3) - 1 表示剩余的 buf3 空间大小,读取内容不会超过这个大小。
  • read_returnread 函数的返回值,用于判断读取是否成功。

总结

这段代码演示了如何使用 C 语言的文件操作函数来打开、读写和合并文件内容,并提供了详细的解释和注释,方便读者理解代码的逻辑和原理。

C语言文件操作:合并多个文件内容

原文地址: https://www.cveoy.top/t/topic/qj9L 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录