C++文件操作

来源:互联网 发布:域名查询软件末注册 编辑:程序博客网 时间:2024/06/06 20:15
1.写入到文本文件
必须包含头文件fsream,fstream中定义了一个用于ofstream类,但要事先声明自己的ofstream对象,必须指明命名空间std,需要将ofstream对象用open()方法和文件关联起来,使用完文件后用close()方法将其关闭。
       程序实例:
#include "stdafx.h"
#include
#include

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char mobile[50];
int year;
double a_price;
double d_price;
ofstream outFile;   //声明对象
outFile.open("mobile.txt");     //关联对象和文件
cout<<"enter the make and model of the mobile:";
cin.getline(mobile,50);
cout<<"enter the mobile year:";
cin>>year;
cin.get();
cout<<"enter the price:";
cin>>a_price;
cin.get();
d_price=0.913*a_price;

cout<<fixed;
cout.precision(2);
cout.setf(ios_base::showpoint);
cout<<"make and model:"<<mobile<<endl;
cout<<"year:"<<year<<endl;
cout<<"price"<<a_price<<endl;
cout<<"now price:"<<d_price<<endl;

outFile<<fixed;
outFile.precision(2);
outFile.setf(ios_base::showpoint);
outFile<<"make and model:"<<mobile<<endl;
outFile<<"year:"<<year<<endl;
outFile<<"price"<<a_price<<endl;
outFile<<"now price:"<<d_price<<endl;

outFile.close(); //不需要文件名作为参数
cin.get();

return 0;
}
注:若源文本文件中有其他内容,将清空文件并写入。要不清空,以后补充。
2、读取文本文件
必须包含头文件fsream,fstream中定义了一个用于ifstream类,但要事先声明自己的ifstream对象,必须指明命名空间std,需要将ifstream对象用open()方法和文件关联起来,使用完文件后用close()方法将其关闭。可以使用ifstream对象和get()方法读取一个字符,用getline()方法读取一行字符。检查文件是否成功打开用is_open()方法。可以用fail()、eof()方法检查输入是否成功。
程序实例:
#include "stdafx.h"
#include
#include
#include

using namespace std;
const int size=60;
int _tmain(int argc, _TCHAR* argv[])
{
char filename[size];
cout<<"enter filename:";
cin.getline(filename,size);
ifstream inFile;
inFile.open(filename);
if(!inFile.is_open())
{
cout<<"can't open file:" << filename<<endl;
cin.get();
exit(EXIT_FAILURE);
}
double value;
double sum=0.0;
int count=0;
inFile>>value;
while(inFile.good())
{
++count;
sum+=value;
inFile>>value;
}
if(inFile.eof())
cout<<"end of file"<<endl;
else
if(inFile.fail())
cout<<"data mismatch"<<endl;
else
cout<<"unknown reason"<<endl;
if(count==0)
cout<<"no data"<<endl;
else
{
cout<<"count"<<count<<endl;
cout<<"sum"<<sum<<endl;
cout<<"ave"<<sum/count<<endl;
}
inFile.close();
cin.get();
return 0;
}
0 0
原创粉丝点击