C++ fstream类读写文件(附带实例)
对文件进行操作时,最常见的就是读写文件。例如,使用程序查看文件内容时,首先要读取文件;修改文件内容时,需要向文件中写入数据。
C++ 中的文件流分为 3 类,即输入流、输出流和输入/输出流,相应地,必须将流声明为 ifstream、ofstream 和 fstream 类的对象:
fstream 类中常用的成员函数如下,其中,参数 c、str为 char 型,n 为 int 型:
	
		
【实例 1】创建一个文本文件 test.txt,并向此文件写入字符串,具体代码如下:
前面介绍了如何写入文件信息,下面通过实例介绍如何读取文本文件的内容。
【实例 2】读取实例 1 中的 test.txt。代码如下:
	
	
C++ 中的文件流分为 3 类,即输入流、输出流和输入/输出流,相应地,必须将流声明为 ifstream、ofstream 和 fstream 类的对象:
ifstream ifile; // 声明一个输入流 ofstream ofile; // 声明一个输出流 fstream iofile; // 声明一个输入/输出流声明了流对象之后,可以使用 open() 函数打开文件。打开文件就是在流与文件之间建立一个连接。接下来讲解如何用 fstream 类读写文件。
fstream 类中常用的成员函数如下,其中,参数 c、str为 char 型,n 为 int 型:
| 函数/方法 | 描述 | 
|---|---|
| get(c) | 从文件中读取一个字符。 | 
| getline(str, n, '\n') | 从文件中读取字符并存入字符串 str 中,直到读取第 n-1 个字符或遇到 '\n' 时结束。 | 
| peek() | 查找下一个字符,但不从文件中取出。 | 
| put(c) | 将一个字符写入文件。 | 
| putback(c) | 对输入流放回一个字符,但不保存。 | 
| eof | 如果读取超过 eof,返回 true。 | 
| ignore(n) | 跳过 n 个字符,参数为空时,表示跳过下一个字符。 | 
【实例 1】创建一个文本文件 test.txt,并向此文件写入字符串,具体代码如下:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    fstream file("test.txt",ios::out);
    if(!file.fail())
    {
        cout << "start write " << endl;
        file << "https://";
        file << "c.biancheng.net";
        file << "/c/" << endl;
    }
    else
    {
        cout << "can not open" << endl;
        file.close();
        return 0;
    }
}
程序通过 fstream 类的构造函数打开文本文件 test.txt,然后向其中写入字符串“https://c.biancheng.net”。前面介绍了如何写入文件信息,下面通过实例介绍如何读取文本文件的内容。
【实例 2】读取实例 1 中的 test.txt。代码如下:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    fstream file("test.txt",ios::in);
    if(!file.fail())
    {
        while(!file.eof())
        {
            char buf[128];
            file.getline(buf,128);
            if(file.tellg()>0)
            {
                cout << buf;
                cout << endl;
            }
        }
    }
    else
        cout << "can not open" << endl;
    file.close();
    return 0;
}
程序的执行结果为:
https://c.biancheng.net/c/
 
	 ICP备案:
 ICP备案: 公安联网备案:
 公安联网备案: