Файлы С++
Файлы С++
Библиотека fstream
позволяет нам работать с файлами.
Чтобы использовать fstream
библиотеку, включите как стандартный, так и <iostream>
заголовочный<fstream>
файл:
Пример
#include <iostream>
#include <fstream>
В библиотеку включены три класса 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 |
Создать и записать в файл
Чтобы создать файл, используйте класс ofstream
или 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();
}
Почему мы закрываем файл?
Это считается хорошей практикой и может очистить ненужное пространство памяти.
Прочитать файл
Для чтения из файла используйте класс ifstream
или fstream
и имя файла.
Обратите внимание, что мы также используем while
цикл вместе с getline()
функцией (которая принадлежит ifstream
классу) для чтения файла построчно и для печати содержимого файла:
Пример
// Create a
text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// 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();