如何用C语言加载目录中的文件名?自制文件处理工具遇阻
Hey there! Sounds like you've got most of the core functionality sorted for your workflow tool—nice work so far. Let's figure out how to load filenames from a specified directory, since that's the piece you're missing.
Since standard C doesn't include a cross-platform directory traversal API, we'll break this down by the two most common platforms you're likely working on: Linux/Unix-like systems and Windows.
dirent.h This is the standard approach for Unix-based systems (Linux, macOS, BSD, etc.). Here's a step-by-step example:
Include the necessary headers:
#include <stdio.h> #include <dirent.h> #include <string.h> #include <limits.h> // For PATH_MAXWrite a function to traverse the directory:
void traverse_directory(const char *dir_path) { DIR *dir = opendir(dir_path); if (!dir) { perror("Failed to open directory"); return; } struct dirent *entry; // Read each entry in the directory while ((entry = readdir(dir)) != NULL) { // Skip the special "." and ".." directories if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } // Now you have the filename in entry->d_name printf("Found file: %s\n", entry->d_name); // Build the full path to the original file (safe buffer handling) char full_path[PATH_MAX]; snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, entry->d_name); // This is where you'd plug in your existing string processing, copy, and delete logic // Example: process the filename, then copy to target folder } closedir(dir); }
Key Notes:
opendir()opens the directory and returns aDIR*handle—always check if it'sNULLand useperror()to debug failures (like permission issues).readdir()returns astruct direntfor each entry;d_nameholds the raw filename string.- Skipping
.and..prevents infinite loops and avoids processing the current/parent directory. - Use
snprintf()instead ofstrcatto build full paths—it prevents buffer overflow by respecting the buffer size.
On Windows, you'll use the FindFirstFile() and FindNextFile() functions from the Win32 API. Here's how to implement it:
Include the necessary headers:
#include <stdio.h> #include <windows.h> #include <string.h>Write a directory traversal function:
void traverse_directory(const char *dir_path) { // Build the search path (add "\\*" to match all files in the directory) char search_path[MAX_PATH]; snprintf(search_path, sizeof(search_path), "%s\\*", dir_path); WIN32_FIND_DATA find_data; HANDLE hFind = FindFirstFile(search_path, &find_data); if (hFind == INVALID_HANDLE_VALUE) { printf("Failed to find files: Error code %lu\n", GetLastError()); return; } do { // Skip "." and ".." directories if (strcmp(find_data.cFileName, ".") == 0 || strcmp(find_data.cFileName, "..") == 0) { continue; } // Filter out subdirectories if you only want to process files if (!(find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { printf("Found file: %s\n", find_data.cFileName); // Build full path to the original file char full_path[MAX_PATH]; snprintf(full_path, sizeof(full_path), "%s\\%s", dir_path, find_data.cFileName); // Plug in your string processing, copy, and delete logic here } } while (FindNextFile(hFind, &find_data) != 0); // Always clean up the file handle when done FindClose(hFind); }
Key Notes:
- We append
\\*to the directory path to tell the API to match all files in the target directory. WIN32_FIND_DATAholds details about each entry;cFileNameis the filename string.- Use
FILE_ATTRIBUTE_DIRECTORYto skip subdirectories if you don't want to process them. - If you need to handle Unicode filenames (common on Windows), switch to
FindFirstFileW()andwchar_tstrings instead.
- Error Handling: Don't skip checking return values for file operations (e.g.,
copyfile()on Unix,CopyFile()on Windows,remove()for deleting originals). This ensures you don't lose files if a copy fails. - Cross-Platform Compatibility: If you want your tool to work on both systems, use preprocessor directives to switch implementations:
#ifdef _WIN32 // Windows-specific code #elif defined(__unix__) || defined(__APPLE__) // Unix/macOS-specific code #endif - Safety First: Always test your tool on a copy of your files first—accidental deletion is no fun!
Hope this helps you get past the directory traversal hurdle—you're almost there!
内容的提问来源于stack exchange,提问作者Saabi Atassi

