将文件名保存为当前时间日期

时间:2015-04-14 08:58:52

标签: c++ datetime

这是我在网上各种教程中找到的一些代码:

#define CURL_STATICLIB
#include <stdio.h>
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include <string>

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main(void) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://localhost/aaa.txt";
    char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}

任何人都可以给我一些关于如何以这样的时间格式保存此文件的指导:

yyyymmddhhmmss

我认为答案是基于这段代码,但我不确定如何实现它:

time_t rawTime

1 个答案:

答案 0 :(得分:3)

我建议将C ++流用于文件。所以示例可能如下所示:

std::time_t t = std::time(nullptr);
std::tm tm = *std::localtime(&t);
std::stringstream filename_stream;
filename_stream << std::put_time(&tm, "%Y%m%d%H%M%S");
std::string file_name;
filename_stream >> file_name;
std::ofstream file(file_name);
file << "File content" << std::endl;