sidrs

OOP Ass 4 - File I/O

Aug 30th, 2024 (edited)
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. using namespace std;
  5.  
  6. int main(){
  7.    
  8.     string data;
  9.     int age;
  10.     ofstream outfile;
  11.     outfile.open("data.dat");
  12.     cout << "Writing to the file... " << endl;
  13.     cout << "Enter your name: ";
  14.     getline(cin, data);
  15.     outfile << data << endl;
  16.     cout << "Enter your age: ";
  17.     cin >> age;
  18.     outfile << age << endl;
  19.     outfile.close();
  20.  
  21.    
  22.     string fdata;
  23.     int fage;
  24.     ifstream infile;
  25.     infile.open("data.dat");
  26.     cout << "\nReading from the file..." << endl;
  27.     getline(infile, fdata);
  28.     infile >> fage;
  29.     cout << fdata << endl;
  30.     cout << fage << endl;
  31.     infile.close();
  32.  
  33.  
  34.     infile.open("ok.dat");
  35.     string contents, line;
  36.     infile.open("ok.dat");
  37.     cout << "\nReading from the file..." << endl;
  38.     while(getline(infile, line)) {
  39.         contents += line + '\n';
  40.     }
  41.     cout << "File Contents:" << endl;
  42.     cout << contents;
  43.     infile.close();
  44.  
  45.     return 0;
  46. }
  47.  
  48. /* OUTPUT:
  49.  
  50. Writing to the file...
  51. Enter your name: John Doe
  52. Enter your age: 99
  53.  
  54. Reading from the file...
  55. John Doe
  56. 99
  57.  
  58. Reading from the file...
  59. File Contents:
  60. ----- BEGIN ok.txt -----
  61.  
  62. Hello World!
  63. Printing entire contents of the file at once.
  64. This is being done by using a while loop.
  65.  
  66. READ
  67. WRITE
  68. OPEN
  69. CLOSE
  70.  
  71. ABCDEFGHIJKLMNOPQRSTUVWXYZ
  72. 1234567890
  73. `~!@#$%^&*()_-=+{}[]\|;:"'<,>.?/
  74.  
  75. ----- END ok.txt ------
  76.  
  77.  
  78. */
  79.  
Advertisement
Add Comment
Please, Sign In to add comment