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
- [C/C++]文件操作
- 文件操作--C 函数操作
- c文件操作
- C文件操作
- C的文件操作
- c语言文件操作
- C的文件操作
- 标准C文件操作
- C#文件操作
- C的文件操作
- C语言文件操作
- C语言文件操作
- C文件操作探索
- [C++]文件读写操作
- C/C++文件操作
- C文件操作
- C语言文件操作
- c文件操作
- Could not obtain transaction-synchronized Session for current thread
- HTTP请求
- 第七章 虚拟机类加载机制
- spring学习笔记(7)AOP前夕[2]CGLib动态代理实例解析
- java回顾篇——java环境的搭建
- C++文件操作
- mybatis打印日志的log4j.xml配置
- swift学习入门笔记1
- 派生类的析构函数
- 给定一个数组,判断从开始能否走到结束,最多需要几步?
- 学习asp.net
- 如何使用 ggplot2?https://www.zhihu.com/question/24779017
- 微信中打开网页,链接无法跳转处理
- 如何在一个函数内修改一个全局变量