Cpp_note_1

Cpp_note_1

Charles Lv7

C++笔记汇总1 文件操作

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <bits/stdc++.h>
using namespace std;
// 1.文本文件
// 写文件
void test01() {
ofstream ofs;
ofs.open(
"D:\\coding_file\\study\\C++_file\\Other_file\\note_file\\Other\\File_"
"Operation\\in.txt",
ios::out);
ofs << "hello world" << endl;
ofs << "hello C++" << endl;
ofs.close();
}
// 读文件
void test02() {
ifstream ifs;
ifs.open(
"D:\\coding_file\\study\\C++_file\\Other_file\\note_file\\Other\\File_"
"Operation\\in.txt",
ios::in);
if (!ifs.is_open()) {
cout << "fail" << endl;
return;
} else {
//四种读数据的方法
//方法1.
char buf[1024] = {0};
while (ifs >> buf) {
cout << buf << endl;
}
// 方法2
/* char buf[1024] = {0};
while (ifs.getline(buf, sizeof(buf))) {
cout << buf << endl;
} */
//方法3
/* string buf;
while (getline(ifs, buf)) {
cout << buf << endl;
} */
// 方法4
/* char c;
while ((c = ifs.get()) != EOF) {
cout << c;
} */
ifs.close();
}
}
//二进制文件
// 写文件
class Person {
public:
char name[64];
int age;
};
void test03() {
ofstream ofs(
"D:\\coding_file\\study\\C++_file\\Other_file\\note_file\\Other\\File_"
"Operation\\b_in.txt",
ios::out | ios::binary);
Person p = {"张三", 18};
ofs.write((const char*)&p, sizeof(p));
ofs.close();
}
//读文件
void test04() {
ifstream ifs(
"D:\\coding_file\\study\\C++_file\\Other_file\\note_file\\Other\\File_"
"Operation\\b_in.txt",
ios::in | ios::binary);
if (!ifs.is_open()) {
cout << "fail" << endl;
return;
} else {
Person p;
ifs.read((char*)&p, sizeof(p));
cout << p.name << endl;
cout << p.age << endl;
}
ifs.close();
}
int main() {
ios::sync_with_stdio(false);
cout.tie(NULL);
test01();
test02();
test03();
test04();
return 0;
}
  • Title: Cpp_note_1
  • Author: Charles
  • Created at : 2022-12-28 12:25:45
  • Updated at : 2023-02-09 09:44:12
  • Link: https://charles2530.github.io/2022/12/28/cpp-note-1/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
Cpp_note_1