计算机程序的输入流起点和输出流的终点都可以是磁盘文件。C++把每个文件都看成是一个有序的字节序列,每个文件都以文件结束标志结束。
按照文件中数据的组织形式可以把文件分为:
- 文本文件:文件中信息形式为ASCII码文件,每个字符占用一个字节;
- 二进制文件:文件中信息的形式与其在内存中的形式相同;
文件操作步骤:
- 打开文件open;
- 检查打开是否成功;
- 读或写read\write;
- 检查是否读完EOF(end of file);
- 使用完文件后关闭文件close;
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
|
#include <iostream> #include <fstream>
using namespace std;
int main() { int a; int index = 0;
fstream fout; fout.open("test.txt", ios::app);
if(fout.fail()) { cout << "open fail" << endl; }
while(cin >> a) { fout << "The numbers are:" << a << endl; index++; if(index == 5) { break; } }
fout.close(); }
|
ios::in |
ifstream的默认模式,打开文件进行读操作 |
ios::out |
ofstream的默认方式,打开文件进行写操作 |
ios::ate |
打开一个已经有输入或输出文件并查找到文件尾 |
ios::app |
打开文件以便在文件的尾部添加数据 |
ios::nocreate |
如果文件不存在,则打开操作失败 |
ios::trunc |
如果文件存在,清除文件原有内容(默认) |
ios::binary |
以二进制方式打开 |
文件的默认打开方式是ASCII,如果需要以二进制方式打开,需要设置ios::binary:
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
|
#include <string> #include <fstream> #include <iostream> using namespace std;
static const int bufferLen = 2048; bool CopyFile(const string& src, const string& dst) { ifstream in(src.c_str(), ios::in | ios::binary); ofstream out(dst.c_str(), ios::out | ios::binary | ios::trunc);
if (!in || !out) { return false; }
char temp[bufferLen]; while (!in.eof()) { in.read(temp, bufferLen); streamsize count = in.gcount(); out.write(temp, count); }
in.close(); out.close();
return true; }
int main() { CopyFile("AA.mp3", "BB.mp3");
return 0; }
|