我有这个功能:
void f_listfiles(char temp[200]){
HANDLE hFind;
WIN32_FIND_DATA FindData;
int i;
hFind = FindFirstFile("*", &FindData);
while (FindNextFile(hFind, &FindData))
{
strcpy(temp, FindData.cFileName);
}
FindClose(hFind);
}
我希望它将目录中的文件名放入char temp。之后我将把它发送到FTP客户端。我怎样才能做到这一点?它目前每次都会覆盖,只有最后一个文件在char temp中。
编辑:我无法使用指针数组,因为我后来需要使用send函数发送此数组(clientSocket,temp,sizeof(temp),0)
答案 0 :(得分:1)
我希望它将文件名放在目录中
char temp[]
这不会起作用:字符数组是单个字符串;你需要一个字符串数组。
也就是说,你需要一个指针数组。有几种方法可以使它工作。一种是让调用者传递一个数组及其长度以避免超出,然后随意分配字符串。您需要返回填写的条目数,否则调用者不会知道数组中实际文件名的结尾。
size_t f_listfiles(char *names[], size_t max) {
HANDLE hFind;
WIN32_FIND_DATA FindData;
size_t i = 0;
hFind = FindFirstFile("*", &FindData);
while (FindNextFile(hFind, &FindData) && i != max)
{
names[i] = malloc(strlen(FindData.cFileName)+1);
strcpy(names[i], FindData.cFileName);
i++;
}
FindClose(hFind);
return i;
}
来电者会像这样调用你的函数:
char *names[200];
size_t count = f_listfiles(names, 200);
for (size_t i = 0 ; i != count ; i++) {
printf("%02d: %s\n", i+1, names[i]);
}
// Caller needs to free dynamically allocated strings:
for (size_t i = 0 ; i != count ; i++) {
free(names[i]);
}
我后来需要将此数组发送到客户端
发送此数组的代码需要以某种方式对其进行序列化 - 比如,在发送之前将字符串逐个附加到字符缓冲区。
答案 1 :(得分:0)
除了 temp 可能太小而无法处理或字符串之外,您可以执行以下操作来克服覆盖问题:
int i = 0;
while (FindNextFile(hFind, &FindData))
{
if(i == 0){
strcpy(temp, FindData.cFileName);
i++;
continue;
}
strcat(temp, FindData.cFileName);
}
或
temp[0] = 0; //terminating null character so strcat can join the strings
while (FindNextFile(hFind, &FindData))
{
strcat(temp, FindData.cFileName);
}
但是有一个 catch 。 strcat
将覆盖 temp 字符串的terminating null character
,并在结果字符串的末尾添加一个新字符串