首页 > 解决方案 > 在C,WINAPI中将日期字符串添加到文件名的开头

问题描述

我正在尝试将日期字符串添加到文件名的开头,但我不明白为什么这不起作用。我有一个获取日期和时间并将其转换为字符串格式的函数,然后我有一个 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;
}

标签: cwindowsapidatefilenames

解决方案


在:

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

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

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

(有关更多建议和错误,请参阅其他评论)


推荐阅读