c - 在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;
}
解决方案
在:
sprintf(file_name, "%s" + (LPARAM)ofn.lpstrFile, s_Date);
请注意,它ofn.lpstrFile
已经指向,file_name
因此您正在覆盖它。在这种情况下,您需要一个单独的(新)缓冲区来构造文件名。
此外,"%s" + (LPARAM)ofn.lpstrFile
不是有效的字符串表达式。利用"%s%s",...
(有关更多建议和错误,请参阅其他评论)
推荐阅读
- sql - 在 sql 模式中保留大量时间数据
- spring - OneToMany 属性不返回其集合的所有元素
- java - 为什么我在 Heroku 上运行我的应用程序时会收到启动超时错误(错误 R10)?
- python - 自定义函数的矢量化未将函数应用于系列的每一行
- vb.net - 范围、命名空间和文件架构
- python - 即使正确安装,Spyder 也无法启动
- sql - sql oracle比较包含子字符串的字符串
- c# - 更改代码以通过单击按钮运行将不起作用
- linux - 如何使用“ls”列出根目录和子目录中的所有文本文件
- c# - WPF - 如何为 ComboBox 触发 MouseLeftButtonUp 事件?