Posted By

browny on 10/20/10


Tagged

file


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

drules


Input/Output with files


 / Published in: C++
 

URL: http://www.cplusplus.com/doc/tutorial/files/

  1. // writing on a text file
  2. #include <iostream>
  3. #include <fstream>
  4. using namespace std;
  5.  
  6. int main () {
  7. ofstream myfile ("example.txt");
  8. if (myfile.is_open())
  9. {
  10. myfile << "This is a line.\n";
  11. myfile << "This is another line.\n";
  12. myfile.close();
  13. }
  14. else cout << "Unable to open file";
  15. return 0;
  16. }
  17.  
  18.  
  19. // reading a text file
  20. #include <iostream>
  21. #include <fstream>
  22. #include <string>
  23. using namespace std;
  24.  
  25. int main () {
  26. string line;
  27. ifstream myfile ("example.txt");
  28. if (myfile.is_open())
  29. {
  30. while ( myfile.good() )
  31. {
  32. getline (myfile,line);
  33. cout << line << endl;
  34. }
  35. myfile.close();
  36. }
  37.  
  38. else cout << "Unable to open file";
  39.  
  40. return 0;
  41. }

Report this snippet   <

You need to login to post a comment.