6.fstream文件打开方式
ios::in 打开一个文件用于输入
ios::out 打开一个文件用于输出
ios::app 所有输出数据附加于文件的末尾
ios::ate 打开一个文件用于输出,如果文件已存在,移动到文件末尾数据可写入文件任何位置
ios::truct 如果文件已存在,丢弃文件内容(ios::out默认的方式)
ios::binary 打开一个文件用于二进制输入输出
View Code
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream inout;
char content[50];
inout.open("C:/score.txt",ios::out); //ios::out带覆盖的写入
inout<<"Danon 1991-01-01 100";
inout.close();
inout.open("C:/score.txt",ios::out|ios::app); //ios::app只追加,不覆盖
inout<<"Jake 1991-01-01 100";
inout.close();
inout.open("C:/score.txt",ios::in);
while(!inout.eof())
{
inout>>content;
cout<<content<<endl;
}
return 0;
}
7.检验流状态
ios::eofbit 当到达文件末尾时置位
ios::failbit 当操作失败时置位
ios::hardfail 当发生不可恢复错误时置位
ios::badbit 当试图进行非法操作时置位
ios::goodbit 当操作成功时置位
流状态函数
eof()
fail()
bad()
good()
clear() 将所有标志位复位
View Code
#include<iostream>
#include<fstream>
using namespace std;
void showState(fstream &);
int main()
{
fstream inout;
inout.open("C:/score.txt",ios::out);
inout<<"Dallas";
cout<<"向文件中正常写数据"<<endl;
showState(inout);
inout.close();
inout.open("C:/score.txt",ios::in);
char content[50];
inout>>content;
cout<<"正常读文件"<<endl;
showState(inout);
inout.close();
cout<<"试图读关闭的文件,错误"<<endl;
inout>>content;
showState(inout);
return 0;
}
void showState(fstream & stream)
{
cout<<"Stream status: "<<endl;
cout<<" eof(): "<<stream.eof()<<endl;
cout<<" fail(): "<<stream.fail()<<endl;
cout<<" bad(): "<<stream.bad()<<endl;
cout<<" good(): "<<stream.good()<<endl;
}
8.二进制的输入和输出
读写二进制文件的时候必须用read和write函数
write函数的语法
streamObject.write(char *address,int size)
View Code
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream binaryio;
binaryio.open("C:/score.dat",ios::out|ios::binary);
char s[]="Altanta 1991-01-01 100";
binaryio.write(s,25);
binaryio.close();
return 0;
}
C++通常用reinterpret_cast运算符来写入非字符数据
reinterpret_cast
dataType: 希望转换出的数据类型
address: 输出数据的起始地址
View Code
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream binaryio;
binaryio.open("C:/score.txt",ios::binary);
int value=199;
binaryio.write(reinterpret_cast<char*>(&value),sizeof(value));
//将int型地址转化成char*型
binaryio.close();
return 0;
}
dat.二进制文件
txt.文本文件
read函数的用法
streamObject.read(char *address,int size)
View Code
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream binaryio;
binaryio.open("C:/score.dat",ios::in|ios::binary);
char s[50];
binaryio.read(s,25);
cout<<s<<endl;
binaryio.close();
return 0;
}
View Code
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream binaryio;
binaryio.open("C:/score.dat",ios::in|ios::binary);
int value;
binaryio.read(reinterpret_cast<char*>(&value),sizeof(value));
cout<<value<<endl;
binaryio.close();
return 0;
}
原文链接: https://www.cnblogs.com/0101gyy/archive/2012/09/29/2708942.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/64106
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!