streaming in from a file

I am learning about streaming in from a file. Right now i have 2 questions.



how do i make sure that the program does not overwrite the file each time i run it ?

how do i make sure that the program displays everything in the file, right now it would only display the name for some reason.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <fstream>
#include <iostream>
using namespace std;
 
int main () {
    
   char data[100];

   // open a file in write mode.
   ofstream outfile;
   outfile.open("afile.dat");

   cout << "Writing to the file" << endl;
   cout << "Enter your name: "; 
   cin.getline(data, 100);

   // write inputted data into the file.
   outfile << data << endl;

   cout << "Enter your age: "; 
   cin >> data;
   cin.ignore();
   
   // again write inputted data into the file.
   outfile << data << endl;

   // close the opened file.
   outfile.close();

   // open a file in read mode.
   ifstream infile; 
   infile.open("afile.dat"); 
 
   cout << "Reading from the file" << endl; 
   infile >> data; 

   // write the data at the screen.
   cout << data << endl;
   
   // again read the data from the file and display it.
   infile >> data; 
   cout << data << endl; 

   // close the opened file.
   infile.close();

   return 0;
}
you can add a time-stamp to the file name if you do not want to over-write the old one.

The display needs to loop over the whole file. You are only reading one entry and then stopping in the write out part.


you can read and write the whole file at once with .read() into a single string, opening the file in binary mode. If you want to do that.
Last edited on
there is also a problem at the line 38:

cout << "Reading from the file" << endl;
//infile >> data;
cout << data << endl;

for some reason a space char is displayed as a new line character.
Topic archived. No new replies allowed.