-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfiles.cpp
More file actions
41 lines (35 loc) · 1.63 KB
/
files.cpp
File metadata and controls
41 lines (35 loc) · 1.63 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <fstream> // чтение или запись в файл
/// или ifstream -- для чтения
/// или ofstream -- для записи
using namespace std;
inline void check(bool, string);
int main() {
fstream fs("fileToRead.txt", ios_base::in);
check(fs.is_open(), "Не могу открыть файл на чтение");
for (string str; getline(fs, str);) {
cout << str << endl;
}
/// Также можно читать/писать посимвольно через .get()/.put()
/// Либо через операторы >> и <<
check(!fs.bad(), "Какие-то ошибки при работе с файлом");
check(fs.eof(), "Должен был быть достигнут конец файла");
check(!fs.good(), "Невозможно, если до сюда дошли"); // good() это не !bad(), см. документацию
fs.close();
fs.open("fileToWrite.txt", ios_base::out | ios_base::app);
check(fs.is_open(), "Не могу открыть файл на запись");
for (int i = 0; i < 7; i++) {
fs << i << endl;
}
fs.close();
/// в данном случае .close() в принципе не обязательна:
/// во-первых, она автоматически вызывается деструктором
/// во-вторых, при любом завершении процесса система сама разберётся
return 0;
}
inline void check(bool cond, string errMsg) {
if (!cond) {
cerr << errMsg << endl;
exit(EXIT_FAILURE);
}
}