
- 二进制文件 存放的是数据在内存中保存的形式
-
文本文件
文件句柄、
<<>>操作符的使用 写文件
ofstream- 读文件
ifstream - 使用
string.c_str()传入句柄函数 - 句柄函数使用
ios::in和ios::out```cppinclude
include
include
using namespace std;
int main() { // 写文件 string filename; cout << “input filename: “; cin >> filename; // 将string转换为函数参数 ofstream f1(filename.c_str(), ios::out); f1 << “hello!” << endl; f1.close(); // 读文件 ifstream f2(filename.c_str(), ios::in); string s; f2 >> s; cout << s << endl;
return 0;
}
<a name="kXLGG"></a>## 读取带空格的字符使用`getline(file, string)` --- `getline` 不会读取回车```cpp#include <iostream>#include <string>#include <fstream>using namespace std;int main() {string filename;cout << "input filename: ";cin >> filename;// 读文件ifstream f2(filename.c_str(), ios::in);string s;getline(f2, s);cout << s << endl;f2.close();return 0;}
f.eof() 判断文件尾
读取一个完整文本文件的内容,文件有多行内容,分行读入
#include <iostream>#include <string>#include <fstream>using namespace std;int main() {string filename, s;cout << "input filename: ";cin >> filename;// 读文件ifstream f2(filename.c_str(), ios::in);while(!f2.eof()) {getline(f2, s);cout << s << endl;}f2.close();return 0;}
在上例中,每读取一个字符,文件指针自动向后移动。当文件指针移动到文件末尾时, f.eof() 返回真,结束读取
英汉词典例子

输入一个单词,在字典中查找
#include <iostream>#include <string>#include <fstream>using namespace std;int main(){ifstream f("英汉词典.txt", ios::in);string line_str, word2find, word;string::size_type pos;cout << "Input a word: " << endl;cin >> word2find;while (!f.eof()){getline(f, line_str);if (line_str.find(word2find, 0) != string::npos){pos = line_str.find(" ", 0);word = line_str.substr(0, pos);if (word2find == word){cout << line_str << endl;break;}}}if (f.eof())cout << "Not found\n";f.close();return 0;}
二进制文件

句柄函数ios::binary read()和write() 需要强制类型转换 char*
#include <iostream>#include <string>#include <fstream>using namespace std;int main(){string s = "Hello!";ofstream f1("f2.dat", ios::binary);f1.write((char *)s.c_str(), s.size());f1.close();ifstream f2("f2.dat", ios::binary);// seek get 寻找读指针,第二个参数是偏移量f2.seekg(0, ios::end);// tellg() 返回当前的位置,而当前就是文件尾,所以返回文件长度string::size_type n = f2.tellg();string ss(n, ' '); // 需要先给ss分配空间,不然读取出错// 现在文件指针在文件尾,什么都读不到,要把文件指针只想文件头f2.seekg(0, ios::beg);// 读出来之前需要求读取的长度f2.read((char *)ss.c_str(), n);f2.close();cout << ss << endl;return 0;}
二进制文件操作一般步骤
- 写操作 —- 创建句柄,
f.write() - 读操作 —- 创建句柄,
f.seekg(0, ios::end)string::size_type拿到文件的长度,f.seekg(0, ios::beg)重新定位文件指针,f.read()拷贝文件
```cppinclude
include
include
using namespace std;
int main() { string filename1, filename2; cout << “Input filename1: “; cin >> filename1; cout << “Input filename2: “; cin >> filename2;
ifstream f_read(filename1.c_str(), ios::binary);ofstream f_write(filename2.c_str(), ios::binary);string s;f_read.seekg(0, ios::end);string::size_type n = f_read.tellg();f_read.seekg(0, ios::beg);f_read.read((char*)s.c_str(), n);cout << s << endl;f_write.write(filename2.c_str(), n);f_read.close();f_write.close();return 0;
} ```
