Search code examples
cbinaryfilesfwrite

fwrite creates an output file that is bigger than the input file


I want to read a file bytewise into an array and then write the data of the array reversed in a new file (program takes filename over command line argument). Tried it with an txt-file and it worked, but if I try it on a jpg-file the new file is bigger than the original! The determined file size saved in long size; is also correct for jpg-files and write loop get size-time executed writing one char (char is one byte big, I am right?). Does anybody know how the output file can get bigger than size*byte?

It doesn't seem logical to me!

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

int main(int argc,char* argv[])
{

 FILE *file;
 char *buffer;
 long size;
 char filename[32];

 if(argc>1)
 {
  //determine file size
  file=fopen(argv[1],"r");
  fseek(file,0,SEEK_END);
  size=ftell(file);
  rewind(file);
  if(size>33554432) //32MB
  {
   fclose(file);
   return 0;
  }

  //create buffer and read file content
  buffer=malloc(33554432);
  fread(buffer,1,size,file);
  fclose(file);

  //create new file name and write new file
  strcpy(filename,argv[1]);
  strcat(filename,"_");
  file=fopen(filename,"w");
  {
   long i;
   for(i=size-1;i>=0;i--)
   {
    fputc(buffer[i],file);
   }
  }
  fclose(file);
  free(buffer);

 }
 return 0;
}

Solution

  • The comments you're receiving are implying something: the newline character \n works differently in text mode on Windows compared with some other systems.

    fputc('\n', file) on Windows actually writes two bytes if file was opened in text mode "w", as if you did fwrite("\r\n", 1, 2, file). This means for any \n byte read by fread, you're writing two bytes back.

    If you want to write binary data back, you need to open your output file using the mode "wb" to fopen(). You also need to open it for reading in binary mode, "rb".