在C++中进行文本的数据写入程序中,首先需要了解整个流程的具体过程。
1.添加必须的头文件:#include <fstream>。
2.定义相应的变量,用于存储文件写入的数据。
3.创建一个ofstream对象。
4.将ofstream与文本文件进行关联。
5.使用ofstream对象和<<运算符进行数据写入。
6.使用完ofstream对象后关闭。
代码实例:
#include <iostream>
#include <fstream>
int main()
{
using namespace std;
char arr[50];
int year;
double price;
ofstream outFile; // create object for output
outFile.open("info.txt"); // associate with a file
cout << "Enter the published place of the book: ";
cin.getline(arr,50);
cout << "Enter the model year: ";
cin >> year;
cout << "Enter the original asking price: ";
cin >> price;
// display information on screen with cout
cout << fixed;
cout.precision(2);
cout.setf(ios_base::showpoint);
cout << "Place: " << arr << endl;
cout << "Year: " << year << endl;
cout << "Price:" << price << endl;
// now do exact same things using outFile instead of cout
outFile << fixed;
outFile.precision(2);
outFile.setf(ios_base::showpoint);
outFile << "Place: " << automobile << endl;
outFile << "Year: " << year << endl;
outFile << "Price: " << a_price << endl;
outFile.close(); // done with file
return 0;
} 上述程序运行之后,会在目标文件夹中生成一个info.txt的文本文件,如果之前此文件夹中没有存在这个文件的话,并且文本中的数据和控制台输出的数据相同。
但是,如果在程序运行之前,目标文件夹中就存在info.txt这个文件,则原先文本中的所有数据将被清除,将文本长度默认截断为零。
还存在一种可能性就是,打开已存在的文件失败,原因可能是没有权限或者是文件已损坏等等。这样的话,这个程序基本就over了。所以在打开文件的时候,进行文件是否打开正常的判断非常重要。
原文:http://blog.csdn.net/wzqnls/article/details/42169577