Search code examples
c++fileio

Using I/O streams to read from one file and write to another


I'm going through a text-book where an exercise entails copying text from one file and write it's lower-case equivalent to another file. I can't seem to find a way to do that using just I/O streams (most of the solutions I found online use stream buffers).

My code is this

int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';

cin >> f_name1>>f_name2;
ofstream fs{ f_name1 };
ifstream fsi{f_name1};
ofstream fs2{f_name2};

fs << "LoRem ipSUM teXt TaXi";

char ch;

while (fsi.get(ch)) {


    fs2 << ch;
}

After running nothing is written to the second file (f_name2). It's just a blank file.

Edit:

This doesn't work either

int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';

cin >> f_name1>>f_name2;
ofstream fs{ f_name1 };
ifstream fsi{f_name1};
ofstream fs2{f_name2};

fs << "LoRem ipSUM teXt TaXi";

char ch;

while (fsi>>ch) {


    fs2 << ch;
}

}

Solution

  • Hmm. So you're writing to the file and then reading the contents and writing out again. Okay...

    You might need to fs.flush() after the fs << code. The data can be buffered, waiting for a newline character to trigger a flush, or doing one yourself.

    I'd also put in some print statements in your while loop to make sure you're getting what you think you're getting.