Home > database >  How do you swap integers between two files?
How do you swap integers between two files?

Time:04-19

I want to copy integers from file A to file B and then from B to A in c . There is integers 1 2 3 4 5 in file A and B is empty. After running the program file B consists of integers 1 2 3 4 5 while file A is empty somehow. I tried using .clear() and .seekg(0) but it was useless. What have I done wrong?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream A1;
    ofstream B1;

    ifstream B2;
    ofstream A2;
    A1.open("C:\\Users\\User\\Desktop\\A.txt");
    B1.open("C:\\Users\\User\\Desktop\\B.txt");
    int ch;
    while (A1 >> ch)
    {
        B1 << ch << " ";
    }
    A2.open("C:\\Users\\User\\Desktop\\A.txt");
    B2.open("C:\\Users\\User\\Desktop\\B.txt");
    /*B1.clear();
    B2.clear(); ///didn't work
    B2.seekg(0);*/
    while (B2 >> ch)
    {
        A2 << ch << " ";
    }
}

CodePudding user response:

Maybe try calling close() on the streams in between to ensure the pending output is written out before the new streams are opened:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
  ifstream A1;
  ofstream B1;
  A1.open("C:\\Users\\User\\Desktop\\A.txt");
  B1.open("C:\\Users\\User\\Desktop\\B.txt");
  int ch;
  while (A1 >> ch)
  {
    B1 << ch << " ";
  }
  A1.close();
  B1.close();

  ifstream B2;
  ofstream A2;
  A2.open("C:\\Users\\User\\Desktop\\A.txt");
  B2.open("C:\\Users\\User\\Desktop\\B.txt");
  while (B2 >> ch)
  {
    A2 << ch << " ";
  }
  A2.close();
  B2.close();
}

  • Related