Search code examples
cbinaryfopenfwritefseek

Combing two files with binary format


I wrote this code to test to combine two files:

 long getFileSize(char *filename)
{
     FILE* fp=fopen(filename,"rb");
     fseek(fp,0,SEEK_END);
     long size=ftell(fp); 
     fclose(fp); 
     return size;   
}



 long lengthA = getFileSize(argv[1]);
   long lengthB = getFileSize(argv[2]);
   printf("sizeof %s is:%d\n",argv[1],lengthA);
   printf("sizeof %s is %d\n",argv[2],lengthB);

   void *pa;
   void *pb;
   FILE* fp=fopen(argv[1],"rb");
   fread(pa,1,lengthA,fp);
   fclose(fp);
   FILE* fpn=fopen(argv[2],"rb");
   fread(pb,1,lengthB,fpn);
   fclose(fpn);
   printf("pointerA is:%p;pointerB is:%p\n",pa,pb);

   FILE *ff=fopen("test.pack","wb");
   fwrite(pa,1,lengthA,ff);
   fwrite(pb,1,lengthB,ff);
   fclose(ff);

   long lengthFinal = getFileSize("test.pack");

   printf("Final size:%i\n",lengthFinal);

however I don't know if the data is equal to the returned value from getFileSize,the console print clearly says something wrong with it,but I can't figure it out:

sizeof a.zip is:465235
sizeof b.zip is 107814
pointerA is:0x80484ec;pointerB is:0x804aff4
Final size:255270

since I know the length of each file,I can then use fseek to restore them right? that's the idea I was thinking.


Solution

  • *pa and *pb need to point to some memory where the file content shall be read to.

    So, do a malloc for these two buffers with lengthA*sizeof(char) and lengthB*sizeof(char) and pass these allocated buffers to fread:

    pa = malloc(lengthA*sizeof(char));
    pb = malloc(lengthB*sizeof(char));
    ...
    fread(pa,sizeof(char),lengthA,fp);
    ...
    fread(pb,sizeof(char),lengthB,fpn);
    

    Furthermore, fread returns the number of items actually read. Also check this!

    Excerpt from man fread:

    fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).