fork download
  1. // Attached: Lab_6 Program #2
  2. // ===========================================================
  3. // File: Lab6_Program2.cpp
  4. // ===========================================================
  5. // Programmer: Elaine Torrez
  6. // Class: CS 1A
  7. // ===========================================================
  8.  
  9. #include <iostream>
  10. #include <fstream>
  11.  
  12. using namespace std;
  13.  
  14.  
  15. // ==== main ===================================================
  16. // This program writes an array of integers to a binary file
  17. // and then reads the data back into memory and displays it.
  18. //
  19. // Input:
  20. // No user input.
  21. //
  22. // Output:
  23. // The numbers 1 through 10 are written to a binary file and
  24. // then displayed on the screen after being read back.
  25. // ===========================================================
  26.  
  27. int main()
  28. {
  29. const int SIZE = 10;
  30. int numbers[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  31. fstream file;
  32.  
  33. // open the file for binary output
  34. file.open("test.bin", ios::out | ios::binary);
  35.  
  36. cout << "Writing the data to the file.\n";
  37.  
  38. // write the array to the binary file
  39. file.write(reinterpret_cast<char *>(&numbers), sizeof(numbers));
  40.  
  41. file.close();
  42.  
  43. // open the file for binary input
  44. file.open("test.bin", ios::in | ios::binary);
  45.  
  46. // read the contents of the file into the array
  47. cout << "Now reading the data back into memory.\n";
  48.  
  49. file.read(reinterpret_cast<char *>(&numbers), sizeof(numbers));
  50.  
  51. // display the contents of the array
  52. for (int count = 0; count < SIZE; count++)
  53. {
  54. cout << numbers[count] << " ";
  55. }
  56.  
  57. cout << endl;
  58.  
  59. file.close();
  60.  
  61. return 0;
  62.  
  63. } // end of main()
  64.  
  65. // ===========================================================
Success #stdin #stdout 0.01s 5324KB
stdin
Standard input is empty
stdout
Writing the data to the file.
Now reading the data back into memory.
1 2 3 4 5 6 7 8 9 10