[Solved] Reading and writing a file in byte array in C/C++


Make sure you’re checking the actual size. Windows has different ways of showing it.

Compare the “Size” in bytes (e.g.16666) rather than the “size on disk”, which will be rounded up depending on the filesystem.

enter image description here


Update

Your drop box link has this code like this:-

FILE* output = fopen( "test_output.dat", "wb" );
fwrite( fileBuf, 1, fileSize, output );
std::cout<<"\nsaved";

FILE *file2 = NULL;
if ((file2 = fopen( "test_output.dat", "rb")) == NULL)
    std::cout << "Could not open specified file\n";
else
    std::cout << "File opened successfully\n";

long prev2=ftell(file2);
fseek(file2, 0L, SEEK_END);
long fileSize2 =ftell(file2);
fseek(file2,prev2,SEEK_SET);

std::cout << "fileSize" << fileSize2;

Here’s the problem : You don’t fclose the file after writing to it. So when your second fopen tries to determine the file size, there’s still buffered data waiting to be written. Just add fclose(output); after the fwrite. If you don’t do this, the buffered data will only be written at the point when your program exits.

(This is a classic case where the problem was almost impossible to see until you provided a SCCCE – which means the 50+ lines of filereader.cpp, not a massive dropbox file…)

1

solved Reading and writing a file in byte array in C/C++