Метод open
Метод open класса ifstream открывает файл
и связывает его с потоком ввода. Первым параметром метод
принимает путь к файлу, а вторым - режим открытия файла.
Режим открытия может быть комбинацией флагов, таких как
ios::in, ios::binary, ios::ate.
Если файл успешно открыт, поток готов к чтению данных.
Синтаксис
ifstream_object.open(filename, mode)
Пример
Давайте откроем файл data.txt и прочитаем из него
первую строку:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file;
file.open("data.txt");
if (file.is_open()) {
string line;
getline(file, line);
cout << line << endl;
file.close();
} else {
cout << "Unable to open file" << endl;
}
return 0;
}
Результат выполнения кода:
"abcde"
Пример
Давайте откроем файл в бинарном режиме и прочитаем из него один символ:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
file.open("data.bin", ios::in | ios::binary);
if (file.is_open()) {
char ch;
file.get(ch);
cout << ch << endl;
file.close();
} else {
cout << "Unable to open file" << endl;
}
return 0;
}
Результат выполнения кода:
"'a'"