将日期字符串添加到C,WINAPI中文件名的开头

问题描述 投票:0回答:1

我正在尝试在文件名的开头添加日期字符串,但我看不到为什么它不起作用。我有一个获取日期和时间并将其转换为字符串格式的函数,然后有一个GetSaveFileName窗口,以便用户可以将文件保存在窗口框中。当我运行程序时,保存文件时会崩溃。谁能看到我犯了什么错误?

提前感谢

// Set file name
void Set_FileName(HWND hWnd)
{
// This is the structure that creates the windows open/save dialogue system
OPENFILENAME ofn;

// This is the path and filename that the user will select/write
char file_name[100];

// Initial address set to zero?
ZeroMemory(&ofn, sizeof(OPENFILENAME));

ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = hWnd;
// This is the parameter of the file name and location
ofn.lpstrFile = file_name;
// Set the initial file name
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = 100;
// What file types the user can use
ofn.lpstrFilter = "Text Files\0*.TXT\0";
ofn.nFilterIndex = 1;

// Needs a particular linker library to work, libcomdlg32.a
GetSaveFileName(&ofn);

// Update what the current date and time is
Get_Date();

// Add a string to the start of the filename
sprintf(file_name, "%s" + (LPARAM)ofn.lpstrFile, s_Date);
// Update filename
ofn.lpstrFile = file_name;
}

这是日期功能。这里没有任何错误,仅供参考。它更新名为s_Date的全局字符串;

// Function to record the date and time as a string
void Get_Date()
{
// Grab the current time
time_t now = time(0);

// I have no idea what is happening here
tm *ltm = localtime(&now);

// Turn the date into a readable string format
stringstream ss_Date;

ss_Date << 1900 + ltm->tm_year << 1 + ltm->tm_mday << "_" << ltm->tm_hour << ltm->tm_min << "_" << endl;
ss_Date >> s_Date;
}
c windows api date filenames
1个回答
1
投票

输入:

sprintf(file_name, "%s" + (LPARAM)ofn.lpstrFile, s_Date);

请注意,ofn.lpstrFile已经指向file_name,因此您将其覆盖。在这种情况下,您需要一个单独的(新)缓冲区来构造文件名。

此外,"%s" + (LPARAM)ofn.lpstrFile不是有效的字符串表达式。使用"%s%s",...

((请参阅其他评论以获取更多建议和错误)

© www.soinside.com 2019 - 2024. All rights reserved.