Posted By

somada141 on 03/12/10


Tagged

file c stream


Versions (?)

Using fstreams to write and read data #1


 / Published in: C++
 

  1. #include <iostream>
  2. #include <fstream> //necessary to use file streams
  3.  
  4.  
  5. int main (int argc, char * const argv[]) {
  6.  
  7. std::ofstream fout; //creating new output stream without assigning a file
  8. fout.open("output.txt"); //opening a new file in which we will save the data
  9.  
  10. int num = 1500; //a number to save
  11. char name[] = "John Doe"; //we could use a 'string' instead of 'char'
  12.  
  13. //using the ''<<' operator we save the data we want
  14. fout << "Here is a number: " << num << "n";
  15. fout << "Now here is a string: " << name << "n";
  16.  
  17. /*
  18.   * The 'flush()' function synchonized the file with the stream buffer
  19.   * In essense all data in the stream buffer that have not been written yet in the file
  20.   * are now written. This a good way to update the file without using the 'close()' function.
  21.   *
  22.   * Here of course it holds no meaning as it is followed by 'close()'
  23.   */
  24. fout.flush();
  25. fout.close();
  26.  
  27. return 0;
  28. }
  29.  

Report this snippet  

You need to login to post a comment.