文本文件
1、打开文件
.open("***"); //打开文件,实现与文件对象的关联
2、读写文件
.get(ch); //一个字符
.getline(str); //一行数据
当读取到文件末尾时,函数返回值为0。可据此来判断循环结束。
.put(ch);
infile >> str;
outfile << str;
3、关闭文件
.close(); //关闭文件,取消文件与文件 对象的关联
二进制文件
1、.打开文件
open("***");方法默认打开的是文本文件。若是打开二进制文件,需要说明
std::fstream infile, outfile;
infile.open("***", std::ios::in | std::ios::binary);
outfile.open("***",std::ios::out | std::ios::binary);
2、读写文件
infile.read(char *buf, int length);
或infile.read(&str, sizeof(str));
或infile.read(char *buf, 1024*sizeof(char));
infile.gcount(); //函数返回实际读入的字节数
outfile.write(buf,len);
infile.eof(); //当到达文件结束位置时,返回非零值;否则,返回0
3、关闭文件
.close();
<1> txt.cpp
1 #include <fstream>
2 #include <iostream>
3
4 int main()
5 {
6 std::ifstream infile; //从文件对象infile中读取
7 std::ofstream outfile; //写入到文件对象outfile
8
9 infile.open("./temp.txt"); //打开已有的temp.txt文件
10 outfile.open("./temp_bak.txt"); //新建并打开temp_bak.txt文件
11
12 if(!infile || !outfile) //判断文件是否正确打开
13 {
14 std::cout<< "文件打开失败!" <<std::endl;
15 return 0;
16 }
17
18 char ch;
19 while(infile.get(ch)) //循环读取:一个字符
20 {
21 std::cout<< ch; //显示
22 outfile.put(ch); //写入到outfile
23 }
24
25 infile.close(); //关闭文件
26 outfile.close();
27
28 return 0;
29 }
<2> binary.cpp
1 #include <iostream>
2 #include <fstream>
3
4 int main()
5 {
6 std::fstream infile; //从infile文件对象中读入数据
7 std::fstream outfile; //写入到outfile文件对象中
8
9 /* 打开文件,与文件对象infile、outfile分别实现关联,并说明所要操作的是二进制文件 */
10 infile.open("./binary.bat", std::ios::in | std::ios::binary);
11 outfile.open("./binary_bak.bat", std::ios::out | std::ios::binary);
12 if(!infile || !outfile) //判断文件是否正确打开
13 {
14 std::cout<< "文件打开失败!" <<std::endl;
15 return 0;
16 }
17
18 char buf[1024]; //数据读取缓存
19 while(!infile.eof())
20 {
21 infile.read(buf,1024); //从文件中读入 1024Bytes 数据到buf缓存中
22 int len = infile.gcount(); //函数.gcount返回实际读入的 字节数
23 outfile.write(buf,len); //将buf缓存中的数据写入到 文件中
24 }
25
26 infile.close(); //关闭文件,取消文件的关联
27 outfile.close();
28 std::cout<< "二进制文件复制完成!" <<std::endl;
29
30 return 0;
31 }