1// basic file operations
2#include <iostream>
3#include <fstream>
4using namespace std;
5
6int main () {
7 ofstream myfile;
8 myfile.open ("example.txt");
9 myfile << "Writing this to a file.\n";
10 myfile.close();
11 return 0;
12}
1#include <iostream>
2#include <fstream>
3using namespace std;
4
5ifstream file_variable; //ifstream is for input from plain text files
6file_variable.open("input.txt"); //open input.txt
7
8file_variable.close(); //close the file stream
9/*
10Manually closing a stream is only necessary
11if you want to re-use the same stream variable for a different
12file, or want to switch from input to output on the same file.
13*/
14_____________________________________________________
15//You can also use cin if you have tables like so:
16while (cin >> name >> value)// you can also use the file stream instead of this
17{
18 cout << name << value << endl;
19}
20_____________________________________________________
21//ifstream file_variable; //ifstream is for input from plain text files
22ofstream out_file;
23out_file.open("output.txt");
24
25out_file << "Write this scentence in the file" << endl;
1#include <iostream>
2#include <fstream>
3using namespace std;
4int main() {
5 fstream my_file;
6 my_file.open("my_file.txt", ios::out);
7 if (!my_file) {
8 cout << "File not created!";
9 }
10 else {
11 cout << "File created successfully!";
12 my_file << "Guru99";
13 my_file.close();
14 }
15 return 0;
16}
17
1#include<iostream>
2#include<fstream>
3
4using namespace std;
5
6int main() {
7
8 ifstream myReadFile;
9 myReadFile.open("text.txt");
10 char output[100];
11 if (myReadFile.is_open()) {
12 while (!myReadFile.eof()) {
13
14
15 myReadFile >> output;
16 cout<<output;
17
18
19 }
20}
21myReadFile.close();
22return 0;
23}
24
25
1++ cCopy#include <iostream>
2#include <fstream>
3
4using std::cout; using std::ofstream;
5using std::endl; using std::string;
6using std::fstream;
7
8int main()
9{
10 string filename("tmp.txt");
11 fstream file_out;
12
13 file_out.open(filename, std::ios_base::out);
14 if (!file_out.is_open()) {
15 cout << "failed to open " << filename << '\n';
16 } else {
17 file_out << "Some random text to write." << endl;
18 cout << "Done Writing!" << endl;
19 }
20
21 return EXIT_SUCCESS;
22}
23