Copying binary files using fread and fwrite

你。 提交于 2019-12-14 03:30:31

问题


I have a problem when copying binary files using fread and fwrite: the loop runs only two times (40 bytes), but the file length is 160 bytes:

#include <string.h>
#define PER_READ 30
int main(void)
{

    char buffer[500] = { 0 };
    FILE* CSV = fopen( "CSV.csv", "rb" );
    FILE* csvDest = fopen( "CSVDest.csv", "wb" );
    unsigned int finished = 0;
    unsigned int counter = 0;
    do
    {
        finished = fread( buffer, sizeof( char*), PER_READ, CSV );//Read all from CSV to a string name buffer
        finished += PER_READ * counter;
        counter++;
    } while (finished == PER_READ * counter);
    fwrite( buffer, sizeof( char* ), finished, csvDest );// write all to a the file CSVDest

    system( "PAUSE" );
    return (0);
};

回答1:


Your implementation could be a simple loop like this, which repeats until there were no bytes read. Note that sizeof(char*) is wrong - the size of a pointer, and that sizeof(char) is 1 by definition.

#include <stdio.h>                                              // include proper header

#define BUFFSIZE    512                                         // power of 2 is kind to system

int main(void)
{
    char buffer[BUFFSIZE];
    size_t bytes;
    FILE *fin, *fou;
    fin = fopen("CSV.csv", "rb");
    fou = fopen("CSVDest.csv", "wb");
    if(fin == NULL || fou == NULL)
        return 1;                                               // or other action
    while ((bytes = fread(buffer, 1, BUFFSIZE, fin)) != 0) {
        if(fwrite(buffer, 1, bytes, fou) != bytes) {
            return 1;                                           // or other action
        }
    }
    fclose(fou);
    fclose(fin);
    return 0;
}



回答2:


You do:

finished = fread( buffer, sizeof(char), PER_READ, CSV );
finished += PER_READ * counter;

and then you compare:

while (finished == PER_READ * counter);

how do expect this to turn out?




回答3:


    #include <string.h>
#include <stdio.h>
#define PER_READ 30
int main( void )
{
    char buffer[500] = { 0 };
    FILE* CSV = fopen( "CSV.csv", "rb" );
    FILE* csvDest = fopen( "CSVDest.csv", "wb" );
    unsigned int finished = 0;
    unsigned int counter = 0;
    unsigned int numBlocksRead = 0;
    do
    {
        numBlocksRead = fread( buffer, sizeof( char ), PER_READ, CSV );
        finished += numBlocksRead*sizeof( char );
        counter++;
        fwrite( buffer, sizeof( char ), numBlocksRead, csvDest );

    } while (finished == PER_READ * counter);

    fclose( CSV );
    fclose( csvDest );
    system( "PAUSE" );
    return (0);
}


来源:https://stackoverflow.com/questions/37032360/copying-binary-files-using-fread-and-fwrite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!