如何在C中将文件拆分成多个文件?

时间:2014-09-18 10:46:36

标签: c

我正在尝试将文件拆分为多个较小的文件。问题是如果大小(用户给出的)大于缓冲区,程序崩溃否则它工作正常。有人可以帮忙吗?这是代码:

char * buffer = (char *)malloc(400);
FILE *exsistingFile = fopen(filename,"rb"); 

do
{   

    /*reading from a file */    
    bytesRead = fread( buffer, sizeof( char ), size, exsistingFile );

    /*exits if its 0 */ 
    if (bytesRead == 0)
    {
        printf("The reading has finished or the file has no data inside\n");
        return 0;
    } 

    fileCount ++;
    sprintf (newFileName,"%s%04i",output,fileCount);


    /* opening the new file bye the name given by the user */   
    outputFile = fopen(newFileName,"w");



    /*checking whether the file is opened or not*/
     if ( !outputFile )
    {
        printf( "File %s cannot be opened for reading\n", filename );
        return E_BAD_DESTINATION; 
    }

    /*write to file from the buffer*/
    fwrite(buffer,sizeof(char),bytesRead,outputFile);

    /*closing the output file*/
    fclose(outputFile);


    } while ( bytesRead > 0 );

3 个答案:

答案 0 :(得分:1)

size_t currentSize = (size >= 400) ? 400 : size;
size -= currentSize;

然后只发送currentSize

答案 1 :(得分:0)

那么,malloc是一个与用户提供的大小一样大的缓冲区吗?或者只读取和写入400字节的位,直到达到用户给出的大小。

char * buffer = (char *)malloc(400);
FILE *exsistingFile = fopen(filename,"rb"); 

do
{   
    fileCount ++;
    sprintf (newFileName,"%s%04i",output,fileCount);

    /* opening the new file bye the name given by the user */   
    outputFile = fopen(newFileName,"w");

    /*checking whether the file is opened or not*/
    if ( !outputFile )
    {
        printf( "File %s cannot be opened for writing\n", filename );
        return E_BAD_DESTINATION; 
    }

    int workSize = size;
    while (workSize)
    {
        int chunkSize = workSize > 400 ? 400 : workSize;

        /*reading from a file */    
        bytesRead = fread( buffer, sizeof( char ), chunkSize, exsistingFile );
        workSize -= bytesRead;

        /*exits if its 0 */ 
        if (bytesRead == 0)
        {
            printf("The reading has finished or the file has no data inside\n");
            return 0;
        } 

        /*write to file from the buffer*/
        fwrite(buffer,sizeof(char),bytesRead,outputFile);
    }

    /*closing the output file*/
    fclose(outputFile);

} while ( bytesRead > 0 );

这样的事情。除了一些错误,但你明白了。这是家庭作业吗?

答案 2 :(得分:0)

如果size是用户输入,则应根据给定的输入分配缓冲区,而不是使用硬编码值。