按代码 c 拆分文件时出错

Error when split files by code c

本文关键字:出错 文件 拆分 代码      更新时间:2023-10-16

我正在编写一个拆分文件的程序,但是在运行时遇到了一些问题,我不知道如何解决它。
给我一些干扰。所有拆分有时为 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 : %ldn", 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();
}

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

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);
    }