文件名截断只显示第一个字符 [英] Filenames truncate to only show first character

查看:173
本文介绍了文件名截断只显示第一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我关注了这个指南从MSDN如何列出目录中的文件(我使用当前目录)。在我的情况下,我需要把信息在我的包(大小1016的字符数组)的消息部分发送到客户端。当我在客户端和服务器上打印packet.message时,只显示文件名的第一个字符。怎么了?下面是一段代码的相关代码片段:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆