【问题标题】:Error when split files by code c按代码 c 拆分文件时出错
【发布时间】:2015-04-17 15:24:37
【问题描述】:

我正在编写一个拆分文件的程序,但运行时遇到了一些问题,我不知道如何解决。
给我一些指导。有时拆分为 0kb 的所有文件,有时有数据。这让我很困惑。

#include <stdio.h>
#include <stdlib.h>

void main()
{
    char *fn = new char[250];
    char *nfn = new char[250];
    long int size, n, size_per_pack;
    FILE *f, *ft; //file and temp file

    printf("enter the file you want to split with full path : ");
    scanf("%s", fn);
    printf("enter the number of parts you want to split the file : ");
    scanf("%ld", &n);

    f = fopen(fn, "rb");
    if (f == NULL)
    {
        printf("couldn't open file");
        exit(0);
    }

    fseek(f, 0, 2);
    size = ftell(f);
    printf("the size of the file in bytes is : %ld\n", size);

    size_per_pack = size / n;
    rewind(f);
    int m = 0;
    char *s1 = new char[size_per_pack];
    for (int j = 1; j <= n; j++)
    {
        sprintf(nfn, "%s.%d", fn, j);
        ft = fopen(nfn, "wb");
        fread(s1, 1, size_per_pack, f);
        fwrite(&s1, 1, size_per_pack, ft);
        rewind(ft);
        int present = ftell(f);
        int present2 = ftell(ft);
    }
    delete[]s1; 
    delete[]fn; 
    delete[]nfn;
    _fcloseall();
}

【问题讨论】:

  • 那是纯C++,不是C!
  • 你使用有什么原因吗? char *fn = new char[250]; 而不是 char fn[250];std::array&lt;char, 250&gt; fn;,或者最好的:std::string fn;?
  • 一个更有趣的问题是你为什么要用 C++ 编写 C 代码?
  • 我只用动态数组,其余都是C
  • 从什么时候开始fread和fwrite纯C++?他“新建”了一个数组,几乎所有这些都不是纯 C 代码。

标签: c++ file join split


【解决方案1】:

您应该在每次循环迭代后关闭输出文件:

for (int j = 1; j <= n; j++)
    {
        sprintf(nfn, "%s.%d", fn, j);
        ft = fopen(nfn, "wb");
        fread(s1, 1, size_per_pack, f);
        fwrite(s1, 1, size_per_pack, ft);
        fclose(ft);
    }

【讨论】:

  • 我还有 0kb 的文件。
  • @Phát Nguyễn 您在fwrite(&amp;s1, 1, size_per_pack, ft); 中也有错误。请参阅我的更正答案。
  • @Phát Nguyễn 函数 fwrite 需要 const void* ptr 作为第一个参数。你提供char** arg。使用write的例子可以看here
猜你喜欢
  • 1970-01-01
  • 2010-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 2020-01-30
  • 1970-01-01
相关资源
最近更新 更多