Write and Read a file..

Hello there, as a beginner at C++, I have a question about how one could merge the following two codes into one, so as to be able to both write on a file,and read from it..

-Write on a file-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//what to include:
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
  
//main function.
int main()
{
   ofstream file; //the object of the file
   file.open("New_file.txt"); //...Or whatever title
   file << "This is the content of the file \n"; //what is written in the file..
   file.close();
   
   system("pause");
   return 0;
}



-Read a file-
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
  //what to include:
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
using namespace std;
  
  

//main function.
int main()
{
   char filename[20]; //character variable for the user input
   ifstream file; //object of the file
   
   cout << "Type the name of the file that you wish to open...\n";
   cin.getline(filename, 20); //the user input
   file.open(filename); 
   //////////////////////////////////////////////////////////////////////////////// Input of the file name and 'open'
   if(!file.is_open()) 
   {
      exit(EXIT_FAILURE);   //from 'cstdlib' library../just in case..
   }
   //////////////////////////////////////////////////////////////////////////////// Precautions..not necessary
   cout << "Content of the file: " << filename << "\n";
   cout << "---------------------------------------" << endl;
   
   char content[50]; //character variable for the content of the file
   file >> content; 
   
   while(file.good()) //while loop for the content
   {
      cout << content << " ";
      file >> content;               
   }
   
   cout << "\n";  
   cout << "----------------------------------------" << endl;
   //////////////////////////////////////////////////////////////////////////////// Output of the 'file' content
   system("pause");
   return 0;
}

Is that possible and what way?
Thanks..
It is possible. The below link might help. Be carefully, if the position that you are trying to write is occupied, you will replace those contents.


http://www.cplusplus.com/reference/istream/istream/seekg/
Alright, thanks for the help!
Topic archived. No new replies allowed.