1.
Writing to a File
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt"); // Create and open a file
if (file.is_open()) {
file << "Hello, this is a test file.\n";
file << "This is line 2.\n";
file.close(); // Close the file
cout << "File written successfully.\n";
} else {
cout << "Error opening file.\n";
}
return 0;
}
2. Reading from a File
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("example.txt");
string line;
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else {
cout << "Unable to open file.\n";
}
return 0;
}
3. Append to a File
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt", ios::app); // Open in append mode
if (file.is_open()) {
file << "This is an appended line.\n";
file.close();
cout << "Line appended successfully.\n";
} else {
cout << "Error opening file.\n";
}
return 0;
}
4. Check if File Exists and Clear Contents
#include <iostream>
#include <fstream>
#include <filesystem>
using namespace std;
namespace fs = std::filesystem;
int main() {
string filename = "example.txt";
if (fs::exists(filename)) {
cout << filename << " exists. Clearing contents...\n";
ofstream file(filename, ios::trunc); // Open in truncate mode
file.close();
} else {
cout << filename << " does not exist.\n";
}
return 0;
}
5. Read and Write with Structures (Binary Files)
#include <iostream>
#include <fstream>
using namespace std;
struct Student {
char name[50];
int age;
float gpa;
};
int main() {
Student s1 = {"Alice", 20, 3.8};
// Write binary
ofstream outFile("student.dat", ios::binary);
outFile.write(reinterpret_cast<char*>(&s1), sizeof(s1));
outFile.close();
// Read binary
Student s2;
ifstream inFile("student.dat", ios::binary);
inFile.read(reinterpret_cast<char*>(&s2), sizeof(s2));
inFile.close();
cout << "Student: " << s2.name << ", Age: " << s2.age << ", GPA: " <<
s2.gpa << endl;
return 0;
}