文件操作
C++ 通过以下几个类支持文件的输入输出:
ofstream: 写操作(输出)的文件类 (由ostream引申而来)
ifstream: 读操作(输入)的文件类(由istream引申而来)
fstream: 可同时读写操作的文件类 (由iostream引申而来)
打开文件
1.建立联系
ofstream examplefile("example.txt");//声明类example并与创建的文件example.txt联系
其中examplefile是ofstream的对象,对象(examplefile)第一个操作通常与一个真正的文件(example.txt)联系起来,改文件由一个流对象(该例子为examplefile)来表示(这些类的一个实例),对改对象进行的操作就是对该对象联系的文件操作。
2.判断文件是否打开
examplefile.is_open()//检查一个文件(examplefile对象所联系的文件)是否被顺利打开
3.向文件中写入数据,并关闭文件
examplefile << "This is a line.\n";
examplefile << "This is another line.\n";
examplefile.close();
ps:为防止流对象被销毁时还联系着打开的文件,析构函数一般将会自动调用关闭函数close
代码示例
//建立一个文件并写入内容
#include <fstream>
using namespace std;
int main()
{
ofstream examplefile("example.txt");
if (examplefile.is_open())
{
examplefile << "This is a line.\n";
examplefile << "This is another line.\n";
examplefile.close();
}
return 0;
}
结果:
examplefile.eof();//eof ,它是ifstream 从类 ios 中继承过来的,当到达文件末尾时返回true
文件读取:
examplefile.getline(buffer,100);
//getline,读取一行字符,直到遇见换行符。getline具有返回值:成功:返回读取的字节数 失败:返回-1。
代码示例:
//对文件的读取示例
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main ()
{
char buffer[256]; //定义一个数组,用来存放字符
ifstream examplefile("example.txt"); //声明一个对象与要读的文件联系
if (! examplefile.is_open()) //判断是否打开
{
cout << "Error opening file"; exit (1);
}
while (!examplefile.eof())
{
examplefile.getline(buffer,100);
cout<<buffer<< endl;
}
return 0;
}
read和write函数
分别为istream和ostream的成员函数,前者被ifstream所继承,后者被ostream所继承。
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
const char * filename = "example.txt";
char * buffer;//buffer是一块内存地址,用来存储或读取数据
long size;//size 是一个整数值,表示要从缓存(buffer)中读出或写入的字符数
ifstream file(filename, ios::in|ios::binary|ios::ate);
size = file.tellg();
file.seekg(0, ios::beg);
buffer = new char [size];
file.read(buffer, size);
file.close();
cout <<"the complete file is in a buffer";
delete[] buffer;
return 0;
}