File Handling11
File Handling11
2 #include<iostream>
3 #include<fstream>
4 using namespace std;
5 void writeToFile(char fileName[],char data[])
6 {
7 ofstream fout;
8 fout.open(fileName,ios::out);
9 fout<<data;
10 fout.close();
11 }
12 void readFromFile(char fileName[])
13 {
14 fstream fin;
15 fin.open(fileName,ios::in);
16 if(!fin)
17 {
18 cout<<"\nFile not exist";
19 }
20 else
21 {
22 char x;
23 //fin>>x;
24 /*we need to read the file line-by-line.
25 To do this, we need to loop through each line of the file
26 until all the lines are read,
27 i.e., until we reach the end of the file.
28
29 We use the eof() function for this purpose, which returns
30
31 true - if the file pointer points to the end of the file
32 false - if the file pointer doesn't point to the end of the file
33 For example,
34 while(!fin.eof())
35 {
36 cout<<x;
37 //fin>>x;
38 x=fin.get();
39 }
40
41 */
42 x=fin.get();
43 while(!fin.eof())
44 {
45 cout<<x;
46 //fin>>x;
47 x=fin.get();
48 }
49 }
50 }
51 int main()
52 {
53 writeToFile("sec_B.txt","Arya College Jaiput Kota ");
54 cout<<endl;
55 readFromFile("sec_B.txt");
56
57 }
58
59 /*
60 file opening mode
61
62 Mode Description
63 1 ios::in Opens the file to read .
64 2 ios::out Opens the file to write.
65 3 ios::app Opens the file and appends new content to the end.
66 */
67
68 /*
69 Instead of using ifstream to read from a file and ofstream
70 to write to the file, we can simply use
71 the fstream class for all file operations.
72
73 */