Chad Krasher
Chad Krasher

Reputation: 27

Using handle in winapi c, return with 0 and no errors but it's not printing any file

#include <Windows.h>
#include <stdio.h>
#include <string.h>



int main() {
    WIN32_FIND_DATAW ffd;
    HANDLE hDire = FindFirstFileW(L"C:\\uripersonal\\School\\summerAndroid\\Ex1", &ffd);
    if (hDire == INVALID_HANDLE_VALUE) {
        printf("FindFirstFile failed (%d)\n", GetLastError());
        return 2;
    }
    while (FindNextFileW(hDire, &ffd) != 0) {
        printf("File Name: %ls"  ,ffd.cFileName);
        printf("File Size: %dw"  ,ffd.nFileSizeHigh);
    }
    CloseHandle(hDire);
    return 0;
}   

Unless Its failing (which is not), The while should print every file name + size. Its returning with exit code 0, but nothing printing, the path is valid.

Upvotes: 1

Views: 74

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117318

You will always miss the first file since you just call FindNextFileW directly without printing what FindFirstFile found. You should also add a wildcard if you want all of them.

Example:

#include <Windows.h>
#include <stdio.h>
#include <string.h>

int main() {
    WIN32_FIND_DATAW ffd;
    HANDLE hDire = // note `\\*` added below:
        FindFirstFileW(L"C:\\uripersonal\\School\\summerAndroid\\Ex1\\*", &ffd);
    
    if (hDire == INVALID_HANDLE_VALUE) {
        printf("FindFirstFile failed (%d)\n", GetLastError());
        return 2;
    }

    // use a do-while loop instead of a while-loop:
    do {
        printf("File Name: %ls\t"  ,ffd.cFileName);
        printf("File Size: %dw\n"  ,ffd.nFileSizeHigh);
    } while (FindNextFileW(hDire, &ffd) != 0);
    
    CloseHandle(hDire);
}   

Note that you are only printing the high part of the file size. You need both to get the real size:

DWORD    nFileSizeHigh;
DWORD    nFileSizeLow;

Upvotes: 3

Related Questions