The fstream library allows us to work with files.To use the fstream library, include both the standard and the header file:
Example
#include < iostream >
#include < fstream >
Create and write to a file:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream f;
f.open ( " file.txt " , ios :: out ) ;
if( !f )
cout << " error in creating file ";
else
{
cout << " File created ";
f << " Hi this is OOP ";
cout << " Data written into file ";
f.close();
}
}
Read from a file:
#include
#include
using namespace std;
int main()
{
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough Hiiiiiii!";
// Close the file
MyFile.close();
string myText;
// Read from the text file
ifstream
MyReadFile("filename.txt");
// Use a while loop together with the getline() function to read the file line by line
while ( getline ( MyReadFile , myText ) )
{
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();
}
C++ File Pointers
Every file keeps track of two pointers, which are referred to as get_pointer (in the input mode file) and
put_pointer (in the output mode file). These pointers indicate the current position in the file where
reading or writing will take place.
In C++, random access is achieved by manipulating the seekg(), seekp(), tellg(), and tellp() functions.
The seekg() and tellg() functions allow you to set and examine the get_pointer, and the seekp() and
tellp() functions perform these operations on the put_pointer.
0 Comments