①将输出内容写入到文本中间中:
步骤:?包含头文件fstream #include<fstream>
?创建一个ofstream对象(名字可以随意取,这里去做outFile) ofstream
outFile;
?将创建的对象outFile与某个文件关联起来 outFile.open("automobile.txt");
注意:如果地址是outFile.open("automobile.txt");这种简写形式,说明创
建的文本文件是在在项目目录下;如果想要创建的文本文件不在
项目目录下,在其他地方,可以使用绝对路径。
?就像使用cout一样使用outFile outFile << "My first file!" << endl;
?关闭文件 outFile.close();
注意:close();不需要使用文件名作为参数,因为outFile已经与文件关联
起来了,如果忘记关闭文件,则在程序正常终止时自动关闭文件。
实例:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int year;
char automobile[50];
float o_price;
ofstream outFile;
outFile.open("carInfo.txt");
cout << "Enter the make and model of automobile: ";
cin.getline(automobile, 50);
cout << "Enter the model year: ";
cin >> year;
cout << "Enter the original asking price:";
cin >> o_price;
outFile << "Make and model: " << automobile << endl;
outFile << "Year: " << year << endl;
outFile << "Was asking: $" << o_price << endl;
outFile << "Now asking: $" << 0.9*o_price << endl;
outFile.close();
return 0;
}该程序运行后会在项目目录下产生一个名叫carInfo.txt的文件
carInfo.txt中的内容是:
②将输出内容写入到文本中间中:
步骤:?包含头文件fstream #include<fstream>
?创建一个ifstream对象(名字可以随意取,这里去做inFile) ifstream inFile;
?将创建的对象inFile与某个文件关联起来 inFile.open("automobile.txt");
注意:如果地址是inFile.open("automobile.txt");这种简写形式,说明创
建的文本文件是在在项目目录下;如果想要创建的文本文件不在
项目目录下,在其他地方,可以使用绝对路径。
?就像使用cin一样使用inFile inFile >> value;
?关闭文件 inFile.close();
注意:close();不需要使用文件名作为参数,因为inFile已经与文件关联
起来了,如果忘记关闭文件,则在程序正常终止时自动关闭文件。
实例:
#include <iostream>
#include <fstream> //支持文件I/O
#include <cstdlib> //包含exit()函数的头文件
using namespace std;
int main()
{
char fileName[50];
double value, sum = 0;
int count = 0;
ifstream inFile;
cout << "Enter name of data file: ";
cin.getline(fileName, 50);
inFile.open(fileName);
if(!inFile.is_open()) //判断文件是否打开
{
cout << "The file doesn‘t exit\n";
cout << "Program terminating.\n";
exit(EXIT_FAILURE); //EXIT_FAILURE同操作系统通信的参数,exit()终止程序
}
inFile >> value;
while(inFile.good()) //没到文件尾
{
++count;
sum += value;
inFile >> value;
}
if(inFile.eof())
cout << "The end of file reached.\n";
else if(inFile.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "The program terminated by unknown reasons.\n";
if(count == 0)
cout << "No numbers in this file.\n";
else
{
cout << "Items read: " << count << endl;
cout << "Sum: " << sum << endl;
cout << "Average: " << sum/count << endl;
}
inFile.close();
return 0;
}
scores.txt中的内容如下:
程序运行结果如下图:
c++文件处理ofstream,ifstream,布布扣,bubuko.com
原文:http://blog.csdn.net/liuwei271551048/article/details/21712803