Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve correct folder listing in C++

Tags:

c

winapi

include "stdafx.h"

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

void _tmain(int argc, TCHAR *argv[])
{
   WIN32_FIND_DATA FindFileData;
   HANDLE hFind;
   printf ("Target file is %s.\n", argv[1]);
   
   hFind = FindFirstFile(argv[1], &FindFileData); 
   if (hFind == INVALID_HANDLE_VALUE) 
   {
      printf ("FindFirstFile failed (%d)\n", GetLastError());
       system("pause");
      return;
   } 
   else 
   {
   do
          {
          printf("%s\n",FindFileData.cFileName);            
          }
   while (FindNextFile(hFind,&FindFileData)!=0);
   FindClose(hFind);
   }
   system("pause");
   FindClose(hFind);
}

I need to get a folder list in output, but it gives me the following:

.
.
f
f
f

Actually, my folder listing is:

.
..
file1
file2
file3

Why do i have only first letter of file name? Thanks.

like image 696
Ax. Avatar asked Dec 23 '22 00:12

Ax.


2 Answers

Use _tprintf(TEXT("%s\n"), FindFileData.cFileName).

In your case FindFileData.cFileName is of actual type wchar_t, so with printf you are printing wide character string as if it were ascii.

like image 175
Constantin Avatar answered Dec 24 '22 14:12

Constantin


You're passing a TCHAR* to a function expecting a char*. If you're compiling with TCHAR as wchar_t, every other byte in the string will be 0, so printf will see every other byte as a terminating null.

like image 33
JoeG Avatar answered Dec 24 '22 15:12

JoeG