Visual C++ generate uuid via UuidCreate and CoCreateGuid,get time now,write string to file

FredGrit發表於2024-07-02
// ConsoleApplication3.cpp : This file contains the 'main' function. Program execution begins and ends there.
// 
#pragma comment(lib, "rpcrt4.lib") 
#include <windows.h>
#include <chrono>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <rpcdce.h> 
#include <sstream>
#include <thread>
#include <uuids.h> 
 

using namespace std;

std::string get_time_now()
{
    auto now = std::chrono::system_clock::now();
    time_t raw_time = std::chrono::system_clock::to_time_t(now);
    struct tm tm_info;
    localtime_s(&tm_info, &raw_time);
    std::stringstream ss;
    ss << std::put_time(&tm_info, "%Y%m%d%H%M%S");
    return ss.str();
}

string get_UuidCreate()
{
    RPC_CSTR rpcStr;
    string uuidValue;
    UUID newUUID;
    UuidCreate(&newUUID);
    UuidToStringA(&newUUID, &rpcStr);
    uuidValue = (char*)rpcStr;
    RpcStringFreeA(&rpcStr);
    return uuidValue;
}

std::string get_CoCreateGuid()
{
    std::string result;
    GUID guid;

    if (S_OK == CoCreateGuid(&guid))
    {
        char* buffer = new char[36];
        snprintf(buffer, 36, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
            guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
        result = std::string(buffer);
    } 
    return result;
}

void write_content_to_file(std::string file_name, std::string content_str)
{
    fstream w_file(file_name, std::ios::app);
    if (!w_file.is_open())
    {
        std::cout << "Create or open " << file_name << " failed!" << std::endl;
        return;
    }
    w_file << content_str << std::endl;
    w_file << std::endl;
    std::cout << get_time_now() << ",finished in " << __FUNCSIG__ << std::endl;
}

int main()
{
    std::cout << get_time_now() << ",started in " << __FUNCSIG__ << std::endl;
    std::stringstream ss;
    for (int i = 0; i < 1000000; i++)
    {
        ss << i + 1 << "," << get_UuidCreate() << "," << get_CoCreateGuid() << std::endl;
    }
    std::string file_name = get_time_now() + ".txt";
    write_content_to_file(file_name, ss.str());
    ss = std::stringstream();
    std::cout << ss.str() << std::endl;
    std::cout << get_time_now() << ",finished in " << __FUNCSIG__ << std::endl;
}


 

相關文章