文件操作

  计算机程序的输入流起点和输出流的终点都可以是磁盘文件。C++把每个文件都看成是一个有序的字节序列,每个文件都以文件结束标志结束。

  按照文件中数据的组织形式可以把文件分为:

  1. 文本文件:文件中信息形式为ASCII码文件,每个字符占用一个字节;
  2. 二进制文件:文件中信息的形式与其在内存中的形式相同;

  

文件操作步骤:

  1. 打开文件open;
  2. 检查打开是否成功;
  3. 读或写read\write;
  4. 检查是否读完EOF(end of file);
  5. 使用完文件后关闭文件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);

/*
//可以直接这么写,程序会默认打开
fstream fout("test.txt");
*/

if(fout.fail()) //也可以判断fout是否非空:if(!fout)
{
cout << "open fail" << endl;
}

while(cin >> a)
{
fout << "The numbers are:" << a << endl; //用定义的fout输出到文件
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);

// 判断文件打开是否成功,失败返回false
if (!in || !out)
{
return false;
}

// 从源文件中读取数据,写到目标文件中
// 通过读取源文件的EOF来判断读写是否结束
// 分块读取,不要一下全读进来,防止缓冲区不够用
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;
}