Input/Output with files


/ Published in: C++
Save to your folder(s)



Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.