如何在c++中添加文件末尾的数据

How do I add data at the end of a file in C++?

本文关键字:数据 文件 添加 c++      更新时间:2023-10-16

我遵循了网上的说明,这段代码应该将输入添加到文件'数据库'的末尾。但是当我检查时,数据会覆盖现有数据。请帮忙,这是我的代码:

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();
}

使用说明:

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

ios::out:为输出操作打开。

ios::app:所有输出操作都在文件末尾执行,将内容附加到文件的当前内容。