File Handlingpptx - 250526 - 043141
File Handlingpptx - 250526 - 043141
++
• Stream- abtraction of a device where input /output operations are
performed
Opening a file
• Create a new file
• before reading or writing on file
Closing a File
Void close();
Myfile.close();
Files
• fstream allows us to work with files
• To use the fstream library, include both the standard <iostream> and
<fstream> header
• #include <iostream>
#include <fstream>
Class Description
ofstream Creates and writes to files
ifstream Reads from files
fstream A combination of ofstream and ifstream: creates, reads,
and writes to files
Create and Write To a File
• Use either ofstream or fstream
• #include <iostream>
#include <fstream>
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!";
// Close the file
MyFile.close();
}
Read a File
• Use ifstream or fstream class
• Also use while loop together with the getline() function which belong to the ifstream class
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
ofstream MyWriteFile("filename.txt"); // Create a text file
MyWriteFile << "Files can be tricky, but it is fun enough!"; // Write to the file
MyWriteFile.close(); // Close the file
++
// 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();
}
Mode Flags
Mode Meaning
ios_base::app append output
ios_base::ate Open file for output and move the read/write control to the end of the line
Fstream afile;
Afile.open(“hello.txt”, ios::out|ios::in);
CLOSE FILE
void close;
Or
myfile.close();
READ FILE
string myText;
ifstream MyReadFile("filename.txt");
if(MyReadFile.is_open()){
fstream hello;
hello.open("hello", ios::out);
if(!hello){
cout<<"file not created";
}else{
cout<<"file created successfully";
hello.close();
}
Return 0;}
++
Ofstream myfile(“hello.txt”,);
Cout<<“hellow world”<<endl;
Cout<<“how is the world”;
String name;
String surname;
Int age;
While(cin>>name>>surname>>age){
Myfile<<name<<‘ ’<<surname<<‘ ‘<<age<<endl;}