[most detailed in history] traverse Windows files

Keywords: C Attribute Windows

File traversal

abstract
Windows file traversal and process traversal are very similar. If you don't understand the process traversal suggestions, take a look at my previous two articles Traverse system process and Traversal system process module ! To traverse a file, you need to know the structure of Win32? Find? Data and the API GetCurrentDirectory FindFirstFile FindNextFile FindClose

thinking
I won't go over the idea. As soon as I read the code, I can understand it. The main idea is to get the path of the folder first, then use functions such as strcat to splice the file names you want to traverse, and then use FindFirstFile and FindNextFile to traverse the files. Note: format characters such as *. * *. dll h???. * are similar to regular expressions. They are used to find the specified file. dwFileAttributes keyword is the attribute information of the file

Complete code

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

int main(int args, char *argv[])
{
    HANDLE hFile;
    char path[MAX_PATH];
    char filepath[MAX_PATH];
    WIN32_FIND_DATA fileData;
    GetCurrentDirectory(MAX_PATH, path);
    strcpy(filepath, path);
    strcat(filepath, "\\*.*");
    hFile = FindFirstFile(filepath, &fileData);
    if (hFile != INVALID_HANDLE_VALUE)
    {
        do
        {
            printf("%s: ", fileData.cFileName);
            if (fileData.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
            {
                printf("<CommonFile> ");
            }
            if (fileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                printf("<Directory> ");
            }
            if (fileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
            {
                printf("<Hidden> ");
            }
            if (fileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
            {
                printf("<ReadOnly> ");
            }
            if (fileData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
            {
                printf("<SystemUse> ");
            }
            if (fileData.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY)
            {
                printf("<Temporary> ");
            }
            printf("\n");
        } while (FindNextFile(hFile, &fileData));
    }
    FindClose(hFile);
    system("pause");
    return 0;
}

Compile command gcc file1.c -o file1

Run screenshots

END

Posted by Cailean on Sun, 08 Dec 2019 05:27:14 -0800