本文用于练习文件的写入和读取!!!
题目:
文件的写入和读取
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int size = 5;
int main(int *argc, int **argv)
{
ofstream outFile;
outFile.open("data.txt");//将对象与文件关联
int *num = new int[size];
cout << "输入5个数据:";
for (int i = 0; i < size; i++)//写入文件的内容
cin >> num[i];
for (int j = 0; j < size; j++)
outFile << num[j] << " ";
outFile.close();
ifstream inFile;
inFile.open("data.txt");
if (!inFile.is_open())//判断文件是否成功打开
{
cout << "文件没成功打开" << endl;
exit(EXIT_FAILURE);
}
int *data = new int[size];
for (int k = 0; k < size; k++)
inFile >> data[k];
inFile.close();
cout << "读入的文件内容:";
for (int l = 0; l < size; l++)
cout << data[l] << " ";
delete[] num;
delete[] data;
return 0;
}
所用知识:
C++文件输出的步骤:
(1)#include <fstream>(2)创建一个ofstream对象; (3) 将对象与文件关联起来,使用open()方法;
(4) 类似使用cout使用ofstream对象;
C++读取文件的步骤:
(1)#include <fstream>(2)创建一个ifstream对象; (3) 将对象与文件关联起来,使用open()方法;
(4) 类似使用cin使用ifstream对象;(5)#include<cstdlib> 使用is_open()判断文件是否成功打开;使用good()方法判断读入数据是否发生错误;使用eof()方法判断是否到达文件尾(EOF);使用fail()方法判断EOF类型是否匹配;
参考资料:
《C++ Primer Plus》第6版