读文件采用ifstream
,写文件用ofstream
,这两个类包含在#include <fstream>
中。
读取和写入存有float数据的txt文件
long int number=0;
ifstream ifile; //说明输入文件流对象ifile
ofstream ofile; //说明输出文件流对象ofile
float a=0;
ifile.open( "a.txt" );
ofile.open("b.txt");
while(1){
ifile>>a; //由文件读入数据
ofile_txt<<a<<" ";
number++;
if(ofile_txt.eof()!=0) break; //当读到文件结束时,ifile.eof()为真
//cout<<a<<endl; //屏幕显示
}
ifile.close();
ofile.close();
cout<<"total numbers:"<<number<<endl;
读取和写入存有float数据的二进制文件
long int number=0;
ifstream ifile; //说明输入文件流对象ifile
ofstream ofile; //说明输出文件流对象ofile
float a=0;
ifile.open( "a.bat",ios::binary) );
ofile.open("b.bat",ios::binary));
float b;
while (ifile.peek()!=EOF) {
number++;
ifile.read((char*)&b, sizeof(b));
ofile.write((char*)&b, sizeof(b));
}
ifile.close();
ofile.close();
cout<<"total numbers:"<<number<<endl;
注意:对于二进制文件不能直接用eof()来作为是否到文件尾的判断。需要用peek()函数,peek的意思是看看下一个字符,指针不移动。
文件的打开模式
文件操作时,如果不显示指定打开模式,文件流类将使用默认值。
在 中定义了如下打开模式和文件属性:
ios::app // 从后面添加
ios::ate // 打开并找到文件尾
ios::binary // 二进制模式I/O(与文本模式相对)
ios::in // 只读打开
ios::out // 写打开
ios::trunc // 将文件截为 0 长度
可以使用位操作符 OR 组合这些标志,比如
ofstream logFile(“log.dat”, ios::binary | ios::app);
Reference:
http://blog.csdn.net/lightlater/article/details/6364931
http://blog.csdn.net/hankai1024/article/details/8016374
http://blog.csdn.net/step__by__step/article/details/6866627
http://www.cplusplus.com/reference/istream/istream/peek/