简介

分享代码,记录学习过程

代码

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
42
43
44
45
46
47
48
49
50
#include <bits/stdc++.h>
using namespace std;

int main() {

ofstream outFile("example.txt"); // 创建或打开文件

if (!outFile) {
cerr << "无法打开文件!" << endl;
return 1;
}

outFile << "这是第一行文本\n";
outFile << "这是第二行文本\n";
outFile << 12345 << "\n";

outFile.close(); // 关闭文件


ifstream inFile("example.txt");

if (!inFile) {
cerr << "无法打开文件!" << endl;
return 1;
}

string line;
while (getline(inFile, line)) {
cout << line << endl;
}

inFile.close();

/*
std::ios::in:打开用于读取

std::ios::out:打开用于写入

std::ios::app:追加到文件末尾

std::ios::ate:打开后定位到文件末尾

std::ios::trunc:如果文件存在则截断

std::ios::binary:二进制模式
std::fstream file("data.dat", std::ios::in | std::ios::out | std::ios::binary);
*/
return 0;
}