Harish krupo
Harish krupo

Reputation: 23

c code to split files

I have written a program to split files into multiple part in C. The code below is what I've been using to split text files which work correctly but it isn't able to split .mp3 files:

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

It just creates one file with the name test.mp3.1 and stoped

Upvotes: 1

Views: 4051

Answers (1)

simonc
simonc

Reputation: 42215

char ch;

needs to be

int ch;

You're currently using too small a type for ch, meaning that the first byte with value 0xff is being confused with EOF.

Upvotes: 3

Related Questions