In C++, files are handled using streams. There are three main classes for file operations:
Files must be opened before performing operations and closed when done using .close()
.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt");
file << "Hello, World!";
file.close();
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("example.txt");
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();
return 0;
}
ofstream file("example.txt", ios::app);
file << "Appending text.";
file.close();
#include <iostream>
#include <fstream>
using namespace std;
struct Student {
char name[50];
int age;
};
int main() {
Student s = {"John", 20};
ofstream file("student.dat", ios::binary);
file.write((char*)&s, sizeof(s));
file.close();
return 0;
}
#include
#include
using namespace std;
struct Student {
char name[50];
int age;
};
int main() {
Student s;
// Read from binary file
ifstream file("student.dat", ios::binary);
if (file.read((char*)&s, sizeof(s))) {
cout << "Name: " << s.name << endl;
cout << "Age: " << s.age << endl;
} else {
cout << "Error reading file!" << endl;
}
file.close();
return 0;
}