c代码分割文件

时间:2013-12-24 10:28:34

标签: c file-io

我编写了一个程序,用于将文件拆分为C语言的多个部分。下面的代码是我用来分割正常工作但无法拆分.mp3个文件的文本文件的代码: / p>

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

main()
{
    char fn[250], ch, nfn[250];
    long int size, n, k;
    int i;
    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);

    i = 1;
    k = size/n;
    rewind(f);
    sprintf(nfn, "%s.%d", fn, i);
    ft = fopen(nfn, "wb");
    while(1)
    {
        ch = fgetc(f);
        if (ch==EOF)
            break;
        fputc(ch, ft);
        if (ftell(f)==(i*k))
        {
            i = i+1;
            fclose(ft);
            sprintf(nfn, "%s.%d", fn, i);
            ft=fopen(nfn, "wb");
        }
    }
}

它只创建一个名为test.mp3.1和停止

的文件

1 个答案:

答案 0 :(得分:3)

char ch;

需要

int ch;

您目前使用的ch类型太小,这意味着值为0xff的第一个字节与EOF混淆。