capypad
0 Tage Serie
cpp / beginner
Snippet

Grundlegende Datei-Ein- und Ausgabe

C++ bietet fstream für Dateioperationen. ofstream erstellt und schreibt in Dateien, während ifstream aus Dateien liest. Überprüfe immer mit is_open(), ob eine Datei erfolgreich geöffnet wurde, und schließe Dateien nach Gebrauch, um Systemressourcen freizugeben.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <fstream>
#include <string>
 
int main() {
std::ofstream outFile("data.txt");
if (outFile.is_open()) {
outFile << "Hello, World!" << std::endl;
outFile << "C++ file handling" << std::endl;
outFile.close();
std::cout << "File written successfully!" << std::endl;
}
std::ifstream inFile("data.txt");
std::string line;
if (inFile.is_open()) {
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close();
}
return 0;
}
Erklärung
1
std::ofstream outFile("data.txt");
Erstellt einen Ausgabe-Dateistrom zum Schreiben in 'data.txt'
2
outFile.is_open()
Prüft, ob die Datei erfolgreich geöffnet wurde
3
outFile << "Hello, World!"
Schreibt Text in die Datei mittels Stream-Operator
4
std::ifstream inFile("data.txt");
Erstellt einen Eingabe-Dateistrom zum Lesen aus 'data.txt'
5
std::getline(inFile, line)
Liest eine Zeile pro Aufruf aus der Datei in den String