使用C++做文件处理时常用的几个函数 查看更多见:iii.run
文件的打开与关闭 (open和close函数)
文件读取之前,使用open函数进行打开。文件使用完毕后,使用close命令关闭。
infile.open("E:\\hello.txt");
infile.close();
文件读取与写入(infile >> income,outfile << "income:")
C++中可以调用库
#include<fstream>
之后可以使用,">>"和"<<"输入输出流的形式进行文件的读取
while (infile >> income)
{
if (income < cutoff)
tax = rate1*income;
else
tax = rate2*income;
outfile << "income:"<<left<<setw(6) << income << right<<setw(8) << "Tax:" <<tax<< endl;
}
文件夹/文件的打开
在程序运行完之后,你可能会希望自动将输出的结果文件打开。调 **Windows Exploler **打开一个文件夹,
system("start E:\\tax.out");
E:\tax.out 就是你文件的地址
运行程序demo
读取hello.txt文件内的收入数据,计算税金,并输出到tax.txt中
hello.txt,直接 Ctrl+S 保存到E盘即可
C++代码如下
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
const int cutoff = 6000;
const float rate1 = 0.3;
const float rate2 = 0.6;
void main() {
ifstream infile;
ofstream outfile;
int income, tax;
infile.open("E:\\hello.txt");
outfile.open("E:\\tax.txt");
while (infile >> income)
{
if (income < cutoff)
tax = rate1*income;
else
tax = rate2*income;
outfile << "income:"<<left<<setw(6) << income << right<<setw(8) << "Tax:" <<tax<< endl;
}
infile.close();
outfile.close();
cout << "done"<<endl;
system("start E:\\tax.txt");
}