当前位置:首页 C++ > 正文

c++获取系统当前时间写入txt文件

作者:野牛程序员:2023-08-07 15:22:51 C++阅读 2808

当然,以下是用C++获取系统当前时间并将其写入txt文件的示例代码:

#include <iostream>
#include <fstream>
#include <ctime>

int main() {
    // 获取当前系统时间
    std::time_t currentTime = std::time(nullptr);
    std::tm* localTime = std::localtime(&currentTime);

    // 将时间格式化为字符串
    char timeString[50];
    std::strftime(timeString, sizeof(timeString), "%Y-%m-%d %H:%M:%S", localTime);

    // 打开txt文件以写入时间
    std::ofstream outputFile("current_time.txt");
    if (!outputFile.is_open()) {
        std::cerr << "无法打开文件。" << std::endl;
        return 1;
    }

    // 将时间写入文件
    outputFile << "当前时间:" << timeString << std::endl;

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

    std::cout << "当前时间已写入 current_time.txt 文件。" << std::endl;

    return 0;
}

在这个代码中,使用<ctime>头文件来获取当前系统时间,使用std::time获取当前时间的时间戳,然后使用std::localtime将其转换为本地时间结构tm。接着,使用std::strftime函数将时间格式化为字符串。最后,我们使用std::ofstream打开"current_time.txt"文件,并将格式化后的时间字符串写入文件。文件操作完成后,关闭文件并输出一条消息确认操作成功。

编译并运行这段代码,它将在同一目录下创建一个名为"current_time.txt"的文件,并将当前系统时间写入其中。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击