分割文件的c代码

标签 c file-io

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

#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 的文件并停止

最佳答案

char ch;

需要

int ch;

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

关于分割文件的c代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20759244/

相关文章:

iphone - 如何从 iPhone 中的 C++ 代码调用 C 函数?

c - 如何在c中的unsigned char中以字节为单位移动

c - 在 Windows 上使用 Cmake/CLion 编译 lzma 库的一种简单方法?

java - 使用文件 IO 并使数据以清晰的方式显示

java - 为什么不是所有条目都进入文件?

java - 检查Java中图像是否存在

c - 尝试存储值然后使用 -1 打印结果,但程序自行关闭

c - 我的递归质数函数代码有一些错误

java - 从 CQ5 中的 DAM 访问 XML 文件

java - 如何使用java仅压缩文件夹中的.txt文件?