1 #include <iostream>
2 #include <fstream> // 读写文件的头文件
3 #include <string>
4 using namespace std; 5 /*
6 1 文本文件 写文件 7 1 包含头文件 8 #include <fstream> 9 2 创建流对象 10 ofstream ofs; 11 3 指定路径和打开方式 12 ofs.open(路径, 打开方式); 13 打开方式: 14 ios::in 读文件打开 15 ios::out 写文件打开 16 ios::ate 从文件尾打开 17 ios::app 追加方式打开 18 ios::trunc 如果已经有文件 先删除在撞见 19 ios::binary 二进制方式 20 4 写内容 21 ofs << "写点数据" << endl; 22 5 关闭文件 23 ofs.close(); 24 */
25 void write() { 26 // 1 包含头文件 #include <fstream> 27 // 2 创建流对象
28 ofstream ofs; 29 // 3 指定路径和打开方式
30 ofs.open("text.txt", ios::out); 31 // 4 写内容
32 ofs << "写点数据" << endl; 33 ofs << "写点数据2" << endl; 34 ofs << "写点数据3" << endl; 35
36 // 5 关闭文件
37 ofs.close(); 38 } 39
40 /*
41 2 文本文件 读文件 42 1 包含头文件 43 #include <fstream> 44 2 创建流对象 45 ifstream ifs; 46 3 指定路径和打开方式 47 ifs.open(路径, 打开方式); 48 打开方式: 49 ios::in 读文件打开 50 ios::out 写文件打开 51 ios::ate 从文件尾打开 52 ios::app 追加方式打开 53 ios::trunc 如果已经有文件 先删除在撞见 54 ios::binary 二进制方式 55 4 读取 四种方式 56 ifs << "写点数据" << endl; 57 5 关闭文件 58 ifs.close(); 59 */
60
61 void read() { 62 // 1 头文件 63 // 2 创建流对象
64 ifstream ifs; 65 // 3 打开文件 判断是否打开成功
66 ifs.open("text.txt", ios::in); 67 if (!ifs.is_open()) { 68 cout << "文件打开失败!" << endl; 69 return; 70 } 71 // 4 读数据 四种方式 72 // 第一种方式 73 //char buf[1024] = { 0 }; 74 //while (ifs >> buf) { 75 // cout << buf << endl; 76 //} 77
78 // 第二种 79 //char buf[1024]; 80 //while (ifs.getline(buf, sizeof(buf))) { 81 // cout << buf << endl; 82 //} 83
84 // 第三种 85 //string buf; 86 //while (getline(ifs, buf)) { 87 // cout << buf << endl; 88 //} 89
90 // 第四种 不推荐用
91 char c; 92 while ((c=ifs.get()) != EOF) { 93 cout << c; 94 } 95
96
97 // 5 关闭流
98 ifs.close(); 99 } 100
101 int main() { 102
103 read(); 104
105 system("pause"); 106 return 0; 107 }