How to read that file?

Hello!
Please, is that file ok?

How to get it written out?
Many thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  // basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile.close();
  system("PAUSE");
  return 0;
}


I mean, how to "cout" it?
Last edited on
try this...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  // basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile("example.txt");
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  system("PAUSE");
  return 0;
} 


Manga's program does the same thing as the original program.

You can use std::ifstream to read from a file. You can use the get member function to read the file character by character or you can use std::getline to read the file line by line. If you know how to read from std::cin you know how to read from std::ifstream. You can do it almost exactly the same way.
You might be seeing a race condition; basically the Output Stream operator isn't writing to your file before you get to the point in your code where you close it. You can use the "std::ofstream::flush()": http://www.cplusplus.com/reference/ostream/ostream/flush/ function to synchronize the buffer and the file.
There is no race condition.

Closing the stream (explicitly with close() or implicitly by the destructor) flushes the put area buffer before closing the file.
I mean, how to "cout" it?

Ah, I'm not sure how I missed your edit but you'll want to open the file again with an std::ifstream object and then use the extraction operator ">>" to save the data to a variable. So basically:

1
2
3
4
5
6
7
8
ifstream ReadFile("example.txt");
string Data;

while(!ReadFile.eof())
{
   ReadFile >> Data;
   std::cout << Data;
}


@ JLBorges: Good catch, I had forgotten about that.
If all you want to do is print out the whole file, you could even do
1
2
std::ifstream readFile("example.txt");
std::cout << readFile.rdbuf();
Topic archived. No new replies allowed.