我写了一个程序来减少Windows上的.img文件 . (Win7 MS Visual studio 2010 express)它在阅读时给了我早期的EOF,但只有我写的!如果我不写,我可以阅读整个文件 . 我试过较小的缓冲区大小(4K,8K)我试过fflush无济于事 . 它总是在读取~606496K字节后停止 . 输入文件是7.6G我想要一个4.8G文件:cut_img test_in.img 4800800k test_out.img

我需要一个特殊的编译标志吗?

// Reduce size of SD-card image file

#include <stdio.h>
#include <string.h>

#define MEGABYTE (1024*1024) // Work in megabytes
#define WITH_WRITING
FILE *infile,*outfile;
unsigned char buffer[MEGABYTE];

int main(int argc, char *argv[])
{   unsigned long new_file_size,read_size,write_size,done_size;
    int status,l,work_in_megs;

    infile = fopen(argv[1],"rb");
    if (infile==NULL)
    {   fprintf(stderr,"%s, could not open '%s' for reading\n",argv[0],argv[1]);
        return 1;
    }

    // check if user specified kilobytes
    work_in_megs = 1;
    l = strlen(argv[2]);
    if (argv[2][l-1]=='k' || argv[2][l-1]=='K')
        work_in_megs=0; 
    // get the amount
    status = sscanf(argv[2],"%lu",&new_file_size);
    if (status!=1)
    {   fprintf(stderr,"%s, could not recognize size '%s'\n",argv[0],argv[2]);
        fclose(infile);
        return 1;
    }
    if (work_in_megs)
        new_file_size *= 1024;

    outfile=fopen(argv[3],"wb");
    if (outfile==NULL)
    {   fprintf(stderr,"%s, could not open '%s' for writing\n",argv[0],argv[3]);
        fclose(infile);
        return 1;
    }

    // Copy data using chunks of MEGABYTE, but keep count in kilobytes
    // This also makes that I can use unsigned longs for counting
#ifdef WITH_WRITING
    printf("Real read with writing\n");
#else
    printf("Real read NO writing\n");
#endif

    done_size = 0;
    while (done_size<new_file_size)
    {   read_size = fread(buffer,1,MEGABYTE,infile);
        write_size = read_size;
        // But not beyond the maximum set by the user
        if ( ((done_size<<10)+write_size) > (new_file_size<<10))
            write_size = (new_file_size - done_size)<<10;

#ifdef WITH_WRITING
       status = fwrite(buffer,1,write_size,outfile);
        // fflush(outfile); did not help either!
        if (status!=write_size)  
        {   fprintf(stderr,"\n%s, write error  after ~%dK\n",argv[0],done_size);
            fclose(outfile);
            fclose(infile);
            return 1;
        }
        done_size += write_size>>10; // Keep count in kilo bytes
#else
        // Fake write count
        done_size += read_size>>10;
#endif

        if (read_size!=MEGABYTE)
        { // assume early EOF
          fprintf(stderr,"\n%s, early end-of-inputfile after ~%dK\n",argv[0],done_size);
          break; 
        }
    }
    printf("\nWritten %d Kbytes\n",done_size);
#ifdef WITH_WRITING
    fclose(outfile);
#endif
    fclose(infile);
    return 0;
} // main