質問

Hello, I have some problem with rewriting files using C++. I try to read data from one binary file and write it to another.

{
    // Reading size of file
    FILE * file = fopen("input.txt", "r+");
    if (file == NULL) return;
    fseek(file, 0, SEEK_END);
    long int size = ftell(file);
    fclose(file);
    // Reading data to array of unsigned chars
    file = fopen("input.txt", "r+");
    unsigned char * in = (unsigned char *) malloc(size);
    for (int i = 0; i < size; i++)
        in[i] = fgetc(file);
    fclose(file);

    file = fopen("output.txt", "w+");
    for (int i = 0; i < size; i++)
        fputc((int)in[i], file);
    fclose(file);
    free(in);
}

But it write my buffer and also append some 0xFF bytes to the end of file (it append some bytes for small files, but can append some kilobytes for greater files). In what can be problem?

役に立ちましたか?

解決

You should invest in fread and fwrite and let the underlying libraries and OS handle the looping:

// Reading size of file
FILE * file = fopen("input.txt", "r+");
if (file == NULL) return;
fseek(file, 0, SEEK_END);
long int size = ftell(file);
fclose(file);
// Reading data to array of unsigned chars
file = fopen("input.txt", "r+");
unsigned char * in = (unsigned char *) malloc(size);
int bytes_read = fread(in, sizeof(unsigned char), size, file);
fclose(file);

file = fopen("output.txt", "w+");
int bytes_written = fwrite(out, sizeof(unsigned char), size, file);
fclose(file);
free(in);

If you want to perform an exact copy without any translations of the bytes, open the input file as "rb" and open the output file as "wb".

You should also consider using new and delete[] instead of malloc and free.

他のヒント

This is not really answering your question about where the mistake is, but I think it's a much simpler way of writing from one binary file to another:

ifstream in(inputFile, ios::binary);
ofstream out(outputFile, ios::binary);
if(in.is_open() && out.is_open())
   while(!in.eof())
   out.put(in.get());
in.close();
out.close();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top