Активный
- Тема Автор
- #1
Работа с файлами необходима для сохранения и загрузки данных. Разберем основные операции.
Запись в текстовый файл
Чтение из текстового файла
Работа с бинарными файлами
Проверка существования файла
Добавление в файл
Чтение по словам
Важные моменты:
- Всегда проверяйте открытие файлов
- Закрывайте файлы после использования
- Обрабатывайте ошибки
- Используйте правильные режимы открытия
Правильная работа с файлами обеспечивает надежность программы!
Запись в текстовый файл
Код:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("data.txt");
if(outFile.is_open()) {
outFile << "Hello World" << endl;
outFile << "Это тестовая строка" << endl;
outFile << 123 << endl;
outFile.close();
} else {
cout << "Ошибка открытия файла" << endl;
}
return 0;
}
Чтение из текстового файла
Код:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile("data.txt");
string line;
if(inFile.is_open()) {
while(getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "Ошибка открытия файла" << endl;
}
return 0;
}
Работа с бинарными файлами
Код:
#include <iostream>
#include <fstream>
using namespace std;
struct Person {
char name[50];
int age;
float height;
};
int main() {
// Запись
Person person = {"John", 25, 175.5};
ofstream outFile("person.bin", ios::binary);
if(outFile.is_open()) {
outFile.write(reinterpret_cast<char*>(&person), sizeof(Person));
outFile.close();
}
// Чтение
Person readPerson;
ifstream inFile("person.bin", ios::binary);
if(inFile.is_open()) {
inFile.read(reinterpret_cast<char*>(&readPerson), sizeof(Person));
inFile.close();
cout << "Name: " << readPerson.name << endl;
cout << "Age: " << readPerson.age << endl;
cout << "Height: " << readPerson.height << endl;
}
return 0;
}
Проверка существования файла
Код:
#include <iostream>
#include <fstream>
using namespace std;
bool fileExists(const string& filename) {
ifstream file(filename);
return file.good();
}
int main() {
if(fileExists("data.txt")) {
cout << "Файл существует" << endl;
} else {
cout << "Файл не существует" << endl;
}
return 0;
}
Добавление в файл
Код:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("data.txt", ios::app);
if(outFile.is_open()) {
outFile << "Новая строка" << endl;
outFile.close();
}
return 0;
}
Чтение по словам
Код:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile("data.txt");
string word;
if(inFile.is_open()) {
while(inFile >> word) {
cout << word << " ";
}
inFile.close();
}
return 0;
}
Важные моменты:
- Всегда проверяйте открытие файлов
- Закрывайте файлы после использования
- Обрабатывайте ошибки
- Используйте правильные режимы открытия
Правильная работа с файлами обеспечивает надежность программы!