1// reading a text file
2#include <iostream>
3#include <fstream>
4#include <string>
5using namespace std;
6
7int main () {
8 string line;
9 ifstream myfile ("example.txt");
10 if (myfile.is_open())
11 {
12 while ( getline (myfile,line) )
13 {
14 //use line here
15 }
16 myfile.close();
17 }
18
19 else cout << "Unable to open file";
20
21 return 0;
22}
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>
3#include <cstring>
4#include <process.h>
5using namespace std;
6int main()
7{
8 char name[999]; //Used to store data
9 ofstream writeMode; //Created object of ofstream
10 writeMode.open("name.dat"); //Opened the file in write mode
11 cout<<"******** Writing into file ********"<<endl;
12 cout<<"Enter your name: ";
13 cin.getline(name, 999); //Accepts string with spaces and after spaces eg ____ ____
14 writeMode<<name<<endl; //Putted data inside the file
15 cout<<"Enter your age: ";
16 cin>>name;
17 cin.ignore(); //Wrote because number is accepted :P, may be
18 writeMode<<name<<endl; //Again putted data inside the file
19 writeMode.close(); //Closed the write mode
20 ifstream readMode; //Created object of ifstream
21 readMode.open("name.dat"); //Opened the file in read mode.
22 cout<<"******** Reading into file ********"<<endl;
23 readMode>>name;
24 cout<<name<<endl; //Write the data to the screen
25 readMode>>name; //again read the data from the file and display it
26 cout<<name<<endl;
27 readMode.close(); //Closed the read mode
28 system("pause");
29 return 0;
30}