文件名截断只显示第一个字符 [英] Filenames truncate to only show first character
问题描述
I'm following this guide from MSDN on how to list the files in a directory (i'm using the current directory). In my case I need to put the information in the message part of my packet (char array of size 1016) to send it to the client. When I print packet.message on both the client and server only the first character of the filenames are shown. What's wrong? Here's a snippet of the relevant section of code:
WIN32_FIND_DATA f;
HANDLE h = FindFirstFile(TEXT("./*.*"), &f);
string file;
int size_needed;
do
{
sprintf(packet.message,"%s", &f.cFileName);
//Send packet
} while(FindNextFile(h, &f));
推荐答案
这通常是由于宽字符串错误被视为ASCII字符串。构建目标是UNICODE, cFileName
包含一个宽字符串,但 sprintf()
假设它是一个ASCII字符串。
This is commonly caused by a wide character string being mistakenly treated as an ASCII string. The build is targeting UNICODE and cFileName
contains a wide character string, but sprintf()
is assuming it is an ASCII string.
FindFirstFile()
将映射到 FindFirstFileA()
或 FindFirstFileW()
,具体取决于构建是否针对UNICODE。
FindFirstFile()
will be mapped to either FindFirstFileA()
or FindFirstFileW()
depending if the build is or is not targeting UNICODE.
解决方案是使用 FindFirstFileA()
和ASCII字符串。
A solution would be to use FindFirstFileA()
and ASCII strings explicitly.
请注意&
不需要在 sprintf()
:
sprintf(packet.message, "%s", f.cFileName);
由于应用程序正在使用超出其控制的字符串更安全的 _snprintf()
以避免缓冲区溢出:
As the application is consuming strings that are outside of its control (i.e file names) I would recommend using the safer _snprintf()
to avoid buffer overruns:
/* From your comment on the question 'packet.message' is a 'char[1016]'
so 'sizeof()' will function correctly. */
if (_snprintf(packet.message, sizeof(packet.message), "%s", f.cFileName) > 0)
{
}
这篇关于文件名截断只显示第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!