夜冰儿 2022-12-29 10:26 采纳率: 33.3%
浏览 32
已结题

文件内容分割程序代码

文件内容分割,如有文件test.txt将文件内容平分并分别存储在两个文件test1.txt,test2,txt中(提示:参考平常上机给出cp类似功能代码,可能需要用到 lseek函数或stat函数)

  • 写回答

2条回答 默认 最新

  • ShowMeAI 2022-12-29 10:57
    关注

    下面是一个用于文件内容分割的程序代码,它可以将文件test.txt中的内容平分并分别存储在两个文件test1.txt和test2.txt中。

    • 首先,我们使用fopen函数打开test.txt文件,然后使用fstat函数获取文件大小。
    • 然后我们使用lseek函数将文件指针移动到文件的一半处,这样我们就可以将文件内容分成两半了。
    • 接着,我们使用fopen函数打开两个新文件test1.txt和test2.txt,然后使用fread函数从原文件中读取数据并写入新文件中。
    • 最后,我们使用fclose函数关闭文件。
    #include<stdio.h>
    #include<sys/types.h>
    #include<sys/stat.h>
    #include<fcntl.h>
    #include<unistd.h>
    int main() {
        //打开原文件test.txt
        int fd1 = open("test.txt", O_RDONLY);
        if (fd1 == -1) {
            perror("open test.txt failed");
            return -1;
        }
        //获取原文件大小
        struct stat st;
        int ret = fstat(fd1, &st);
        if (ret == -1) {
            perror("fstat failed");
            return -1;
        }
        off_t file_size = st.st_size;
        //将文件指针移动到文件的一半处
        off_t pos = lseek(fd1, file_size / 2, SEEK_SET);
        if (pos == -1) {
            perror("lseek failed");
            return -1;
        }
        //打开新文件test1.txt
        int fd2 = open("test1.txt", O_CREAT | O_WRONLY, 0644);
        if (fd2 == -1) {
            perror("open test1.txt failed");
            return -1;
        }
        //将文件指针移动到文件的开头处
        ret = lseek(fd1, 0, SEEK_SET);
        if (ret == -1) {
            perror("lseek failed");
            return -1;
        }
        //读取原文件的前一半内容并写入新文件test1.txt
        char buf[1024];
        int n;
        while ((n = read(fd1, buf, sizeof(buf))) > 0) {
            write(fd2, buf, n);
        }
        //关闭文件test1.txt
        close(fd2);
        //打开新文件test2.txt
        int fd3 = open("test2.txt", O_CREAT | O_WRONLY, 0644);
        if (fd3 == -1) {
            perror("open test2.txt failed");
            return -1;
        }
        //打开新文件test2.txt
        int fd3 = open("test2.txt", O_CREAT | O_WRONLY, 0644);
        if (fd3 == -1) {
            perror("open test2.txt failed");
            return -1;
        }
        //读取原文件的后一半内容并写入新文件test2.txt
        while ((n = read(fd1, buf, sizeof(buf))) > 0) {
            write(fd3, buf, n);
        }
        //关闭文件test2.txt
        close(fd3);
        //关闭原文件test.txt
        close(fd1);
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 1月6日
  • 已采纳回答 12月29日
  • 创建了问题 12月29日

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?