如何在C ++的文件末尾添加数据? [英] How do I add data at the end of a file in C++?

查看:811
本文介绍了如何在C ++的文件末尾添加数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经按照网上的说明,这段代码假设将输入添加到文件'数据库'的末尾。但是当我检查,数据超过现有的数据。请帮助,这里是我的代码:

I have followed instructions on the net and this code is suppose to add the inputs to the end of the file 'database'. But when i check, the data over rides the existing data. Please help, here is my code:

int main(){
    string name;
    string address;
    string handphone;
    cout << "Name: ";
    getline(cin, name);
    cout << "Address: ";
    getline(cin, address);
    cout << "Handphone Number: ";
    getline(cin, handphone);
    ofstream myfile("database", ios_base::ate);
    myfile.seekp( 0, ios_base::end );
    myfile << name<<endl;
    myfile << address<<endl;
    myfile << handphone<<endl;
    myfile.close();
}


推荐答案



Use:

ofstream myfile("database",  ios::out | ios::app);

ios :: out :操作。

ios :: app :所有输出操作都在文件末尾执行,当前文件的内容。此标记只能在打开的仅输出操作的流中使用。

ios::app: All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.

这篇关于如何在C ++的文件末尾添加数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆