C++ Slides - 6: File Handling: Formatted I/O, Hierarchy of File Stream Classes, Opening
C++ Slides - 6: File Handling: Formatted I/O, Hierarchy of File Stream Classes, Opening
C++ Slides - 6: File Handling: Formatted I/O, Hierarchy of File Stream Classes, Opening
This is
a simple text
consisting words
numbers 1234.09872
and symbols !@#$%^&*()
// Read characters from file
#include <iostream>
#include<fstream>
using namespace std;
int main() {
char c;
ifstream fin("MySecrets.txt");
if(!fin) {cout<<"File Does not Exist"; return 0; }
while(!fin.eof()) { // eof – end of the file
fin.get(c); cout<<c; // print text on screen
}
fin.close();}
// Writing text into file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream file("Simplefile.txt");
file << "Writing to a file in C++....";
file.close();
}
Working with multiple files
// MyFile.cpp #include “MyFile.cpp”
int MyValue() { #include <iostream>
return -9999; using namespace std;
}
int main() {
cout<<MyValue();
}
File modes
1. ios::app – Always write in the end of a file
2. ios::ate – Take the control at the end just once
3. ios::in - Open a file for reading
4. ios::out - Open a file for writing
5. ios::trunc – remove the old contents
// Writing text into file using ios::out flag
#include <iostream>
#include <fstream>
using namespace std;
int main () {
fstream file("Simplefile.txt“,ios::out);
file << "Writing to a file in C++....";
file.close();
}
// Reading + writing in a file
#include<iostream>
#include<fstream>
using namespace std;
int main(){
string sen;
ofstream fout(“MySecrets.txt”);
fout<<“hello 123”;
fout.close();
ifstream fin(“MySecrets.txt”);
getline(fin, sen); cout<<sen;
fin.close();
}
Q:Try to read and write a file using ios::in and
ios::out
Hint:
fstream fileIO(“MySecrets.txt”,ios::in,ios::out);
You may need file pointers such as seek() and tell() functions
which are covered next.
File pointers – bookmarks in the file
•Get Pointer tells the current location during file reading
•Put Pointer tells the current position during file writing
•A file pointer is not like a C++ pointer but works like a
book-mark in a book
• These pointers help attain random access in file for faster
access in comparison to a sequential access
File pointers – seek and tell
•ios::beg
•ios:cur
•ios:end
Few examples
•fin.seekg(30); or fin.seekg(30, ios::beg);
// go to byte no. 30 from beginning of file