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>
usingnamespace 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;
}
//what to include:
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
usingnamespace 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;
}