C++中将数据添加到文件的末尾

C++中文件的读取需要包含fstream文件,即:#include<fstream>

文件的读取和写入是是通过流操作来的,这不像输入、输出流那样,库中已经定义了对象cin和cout

文件的读取需要声明类的对象:

ofstream write;

ifstream read;

在这两个对象中,ofstream::open或ifstream::open是打开文件的函数,该函数默认以out或in的方式读入或写出,这两种方式都会先清空文件中的数据,如果想在上一次执行该操作的文件后加入数据,那么就要用ios类中的app方法,ios:app

ios::app:打开文件不会清空数据,文件指针始终在文件尾,因此只能在文件尾写数据。

利用这一点就可以实现添加数据到文件尾的方法

举例:

#include<iostream>
#include<fstream>
#include<vector>
 
using namespace std;
 
int main()
{
    int a;
 
    ofstream write;
    ifstream read;
 
    cout << "请输入一个数字:" << endl;
    cin >> a;
 
    write.open("result.txt", ios::app);                //用ios::app不会覆盖文件内容
    write << a << endl;
    write.close();
    read.close();
 
    return 0;

}

--------------------- 
作者:轩落_翼 
来源:CSDN 
原文:https://blog.csdn.net/qq_23880193/article/details/44279283 

猜你喜欢

转载自blog.csdn.net/xikangsoon/article/details/84984662
今日推荐