阶段性总结2(文件操作,STL)

文件操作C++将文件看成无结构字节流。文件可以分为两种类型:1.文本文件:文件以文本的ASCII码形式存储在计算机中。2.二进制文件:文件以文本的二进制形式存储在计算机中,用户一般情况下不能读懂。C++输入/输出标准库 iostream:istream 输入流ostream 输出流iostream 输入/输出流,由上述两个类派生而得;而iostream库中包含的主要头文件就包含f...
摘要由CSDN通过智能技术生成

文件操作
C++将文件看成无结构字节流。
文件可以分为两种类型:
1.文本文件:文件以文本的ASCII码形式存储在计算机中。
2.二进制文件:文件以文本的二进制形式存储在计算机中,用户一般情况下不能读懂。
C++输入/输出标准库 iostream:
istream 输入流
ostream 输出流
iostream 输入/输出流,由上述两个类派生而得;
而iostream库中包含的主要头文件就包含fstream;
对文件操作主要设计以下3类
1.ifstream 文件读(输入)操作类.
2.ofstream 文件写(输出)操作类.
3.fstream 文件读(输入)/写(输出)操作类.
ifstream
#include
#include
#include //ifstream

using namespace std;

int main(){
//对文件进行读(输入)操作
ifstream ifd(“text1.txt”, ios::in);
if(!ifd.is_open()){
cout << "Error: open() " << endl;
exit(1);
}
string str = “”;
while(getline(ifd, str)){//以行为单位从文件流中读取文件,放入str中
cout << str << endl;
}
cout << endl;
ifd.close(); //打开文件后,一定要记得关闭
exit(0);
}
ofstream
#include
#include
#include //ofstream

using namespace std;

int main(){
//对文件进行写(输出)操作
ofstream ofd(“text2.txt”, ios::out | ios::trunc);
if(!ofd.is_open()){
cout << "Error: open() " << endl;
exit(1);
}
string str1 = “hello, world”;
for(auto x : str1){
ofd << x;
}
ofd.close(); //打开文件后一定要记得关闭
cout << endl;

exit(0);

}
fstream
先写后读
#include
#include
#include

using namespace std;

int main(){
//read file
fstream fd(“text1.txt”, ios::in | ios::out | ios::app);
if(!fd.is_open()){
cout << “error: open()” << endl;
exit(1);
}
//先写
string str1 = “\nline4:lalala”;
fd << str1;
//重置文件流指针到文件首
fd.seekg(fd.beg);
//读文件内容
string str = “”;
while(getline(fd, str)){
//从文件流中读取数据放入str中,每次循环会刷新str
if(str.size() == 0) cout << ‘\n’; //读到空格自动换行
cout << str;
}

fd.close();
exit(0);

}
先读后写
在实际中,需要对一个txt文件先读后写,这时可以使用fstream对象、 然后使用流对象的定位函数。seekg,seekp,tellg,tellp来进行相应位置的写。

注意: 在先读后写时,读完这个文件需要对流进行clear操作,否则无法写入。
fstream fd(“text1.txt”, ios::in | ios::out | ios::app);
相当于:
fstream fd;
fd.open(“text1.txt”, ios::in | ios::out | ios::app);
代码:
#include
#include
#include

using namespace std;

int main(){
//read file
fstream fd(“text1.txt”, ios::in | ios::out | ios::app);
if(!fd.is_open()){
cout << “error: open()” << endl;
exit(1);
}
string str = “”;
while(getline(fd, str)){
//从文件流中读取数据放入str中,每次循环会刷新str
if(str.size() == 0) cout << ‘\n’; //读到空格自动换行
cout << str;
}
//由于读操作已经读到了文件的末尾,这时输入流标记为文件结束
//若不清空流标记clear()的话,写操作是写不进去的
//streampos pos = fd.tellg();
//fd.seekg(fd.end);
fd.clear();
string str1 = “\nline7:lalala”;
fd << str1;
fd.close();

exit(0);

}
—二进制文件以基本类型数据在内存的二进制表示形式存放数据, 不对写入或读出的数据做格式转换 。
— 二进制文件的读写方式由程序控制。
—打开二进制文件用binary方式。
—二进制文件是随机存取文件 。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值