Home >Backend Development >C++ >How to append content to the end of a file using C++?

How to append content to the end of a file using C++?

WBOY
WBOYOriginal
2024-06-04 12:02:59875browse

In C++, to append content to the end of a file, you can use the open() and seekg() functions in the fstream library: Use the open() function to open the file in append mode. Use the seekg() function to move the file pointer to the end of the file. Use the insertion operator (

How to append content to the end of a file using C++?

How to use C++ to append content at the end of a file

In C++, you can use the file operation functionfstream The open() and seekg() etc. to append content to the end of the file.

Code example:

#include <fstream>
#include <iostream>

using namespace std;

int main() {
    // 打开文件
    fstream file;
    file.open("my_file.txt", ios::app);

    // 移动文件指针到文件末尾
    file.seekg(0, ios::end);

    // 追加内容
    file << "追加的内容\n";

    // 关闭文件
    file.close();

    return 0;
}

Practical case:

This code can be used to append log information to the log file . For example:

#include <fstream>
#include <ctime>

using namespace std;

int main() {
    // 打开日志文件
    fstream file;
    file.open("log.txt", ios::app);

    // 获取当前时间
    time_t now = time(0);
    tm *ltm = localtime(&now);

    // 将当前时间的日志信息追加到文件中
    file << "[" << ltm->tm_year + 1900 << "-" << ltm->tm_mon + 1 << "-" << ltm->tm_mday << " "
         << ltm->tm_hour << ":" << ltm->tm_min << ":" << ltm->tm_sec << "] 日志信息\n";

    // 关闭日志文件
    file.close();

    return 0;
}

The above is the detailed content of How to append content to the end of a file using C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn