【问题标题】:Getting a file creation date and putting it in a string获取文件创建日期并将其放入字符串
【发布时间】:2014-03-25 14:31:19
【问题描述】:

我正在尝试从文件中读取创建日期,将其存储在字符串中,然后将其输出到格式化的 CSV 文件。 目前,我将无数不同来源的代码拼凑在一起,但徒劳无功,希望它能做我想做的事,但没有什么大惊喜,它没有​​(在 1601 年约会,因为显然至少有一个转换不起作用)。

我正在使用;

char        sourceAfilename[255];  // The name of the source file I want to
                                   // get the creation date of
FILE        sAptr;                 // Pointer to the source file
FILE        o1ptr;                 // Pointer to the output file
std::string sAdateString;          // date field - String   
const char* sAdateText;            // date field - char array
FILETIME    sAfileTime;            // filetime version of the date
SYSTEMTIME  sAsystemTime;           // systemtime version of the date
std::stringstream sAstringStream;   // Temp stringstream
HANDLE      sAhandle                // Handle of the File

// Open the files
// read and write stuff from/to the files

// now get the date of the source file
fileHandle = CreateFile(LPWSTR(sourceAfilename), GENERIC_READ, 0, NULL, OPEN_EXISTING, 
FILE_ATTRIBUTE_NORMAL, NULL);
GetFileTime(sAhandle, &sAfileTime, NULL, NULL);
CloseHandle(sAhandle);
FileTimeToSystemTime(&sAfileTime, sAsystemTime);
sAstringStream << sAsystemTime.wDay << '/' << sAsystemTime.wMonth << '/' << 
sAsystemTime.wYear;
sAdatetext = sAdatestring.c_str();

// Now output the text version of the date to the output file
fputs(" * Creation date is - ", o1ptr);
fputs(sAdatetext, o1ptr);
fputs(" * \n", o1ptr);

如果有人能指出我哪里出错了,或者给我一个简单版本的“获取文件日期并将其存储在 char 数组中”,将不胜感激。

谢谢 理查德

【问题讨论】:

  • sAdatetext = sAdatestring.c_str(); // sAdatestring 从哪里获取数据?

标签: string datetime c++11 type-conversion


【解决方案1】:

既然你说的是 C++11,那么使用 wrl.h 中的 FileHandle

#include <wrl.h>
#include <iostream>
#include <sstream>

namespace wrl = Microsoft::WRL::Wrappers;

int main(int argc, char* argv [])
{
    if (argc != 2)
    {
        printf("This sample takes a file name as a parameter\n");
        return 0;
    }
    wrl::FileHandle hFile (CreateFile(argv[1], GENERIC_READ, FILE_SHARE_READ, NULL,
        OPEN_EXISTING, 0, NULL));

if (!hFile.IsValid())
{
    printf("CreateFile failed with %d\n", GetLastError());
    return 0;
}

FILETIME sAfileTime;
SYSTEMTIME sAsystemTime, stLocal;
GetFileTime(hFile.Get(), &sAfileTime, NULL, NULL);
FileTimeToSystemTime(&sAfileTime, &sAsystemTime);
SystemTimeToTzSpecificLocalTime(NULL, &sAsystemTime, &stLocal);
std::stringstream sAstringStream;
sAstringStream << stLocal.wDay << '/' << stLocal.wMonth << '/' << stLocal.wYear;
// Now output the text version of the date to the output file
puts(sAstringStream.str().c_str());

 std::cout << "\nPress Enter to exit";
 std::cin.ignore();

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多