Home > Software engineering >  I cant merge two files in a third one
I cant merge two files in a third one

Time:02-20

My problem is the following when I show the third file, It shows a lot of 0 and not the ints of file 1 and file 2. My file ends up with 4,00 KB (4.096 bytes) for some reason I don't know. Btw, the third file should have first: the first int of file1 and then the first of file2 and so on

Edit: I was testing the problem, and I realize that the size of the third file is correct before I show it. It's 24 and that's the sum of file1 and file 2. But when I read it, then it goes crazy

 #include <iostream>

using namespace std;
int main()
{
  int buffer1, buffer2, buffer3;
  
  //What is written in file 1 and file 2
  int file1_content[] = {1,3,5};
  int file2_content[] = {2,4,6};

  FILE* f3, *f1, *f2;
  f1 = fopen("archivo1", "rb");
  f2 = fopen("archivo2", "rb");
  f3 = fopen("archivo3", "wb ");
  if(!f1)
  {
      cout<<"Error el archivo 1 no se pudo abrir"<<endl;
      return 1;
  }
  if(!f2)
  {
      cout<<"Error el archivo 2 no se pudo abrir"<<endl;
      return 1;
  }
  if(!f3)
  {
      cout<<"Error el archivo 3 no se pudo abrir"<<endl;
      return 1;
  }

   //write file 1 and file two in file 3
   while(fread(&buffer1, sizeof(int), 1, f1) && fread(&buffer2, sizeof(int), 1, f2) )
   {
      fwrite(&buffer1, sizeof(int), 1, f3);
      fwrite(&buffer2, sizeof(int), 1, f3);
   }
   fclose(f1);
   fclose(f2);

   //show file 3
   while(fread(&buffer3, sizeof(int), 1, f3))
   {
       cout<<buffer3<<" ";
   }
   //EXPECTED OUTPUT
   //1 2 3 4 5 6 
   fclose(f3);

    return 0;
}

CodePudding user response:

Your code has undefined behavior.

According to §7.21.5.3 ¶7 of the ISO C11 standard, when a file is opened in update mode ( ), the following restrictions apply:

  1. Output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind).
  2. Input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.

In your program, you are violating rule #1. The easiest solution would be to add a call to rewind between the calls to fwrite and fread, which you should do anyway, because you want to start reading from the start of the file.

  • Related