- 论坛徽章:
- 5
|
…………………………你确定这个是生产用代码?完全木有错误处理啊!!
下面的代码由我的开源项目lpath中对应代码经过稍加改写得到,主要是剔除掉了Lua相关部分(lpath是平台无关的路径操作例程到Lua语言的绑定库),换掉了错误处理函数(原先是交给Lua处理,这个版本直接打印出来了),因为Lua的错误处理类似异常,会longjmp,所以这个版本看上去要臃肿一些。其实原理是很简单的,很好理解,而且具备扩展性!- #include <stdio.h>
- #include <Windows.h>
- void print_lasterror(const char *title, DWORD errnum) {
- const char *msg;
- FormatMessageA(
- FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL,
- errnum,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (LPSTR)&msg,
- 0, NULL);
- fprintf(stderr, "%s: %s\n", title, msg);
- LocalFree((LPSTR)msg);
- }
- typedef int PathIter(void *ud, const char *path, int isdir);
- int removedir(const char *directory);
- int iterpath(const char *directory, PathIter *iter, void *ud) {
- WIN32_FIND_DATA wfd;
- HANDLE h;
- DWORD errnum;
- char path[MAX_PATH];
- strcpy(path, directory);
- strcat(path, "\\*");
- if ((h = FindFirstFile(path, &wfd)) == INVALID_HANDLE_VALUE) {
- print_lasterror(path, GetLastError());
- return 0;
- }
- do {
- if ( strcmp(wfd.cFileName, ".") == 0 ||
- strcmp(wfd.cFileName, "..") == 0)
- continue;
- if (iter(ud, wfd.cFileName,
- (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
- FindClose(h);
- return 0;
- }
- }
- while (FindNextFile(h, &wfd));
- if ((errnum = GetLastError()) != ERROR_NO_MORE_FILES) {
- print_lasterror("FindNextFile", errnum);
- return 0;
- }
- FindClose(h);
- return 1;
- }
- int remove_iter(void *ud, const char *path, int isdir) {
- char newpath[MAX_PATH];
- strcpy(newpath, (const char*)ud);
- strcat(newpath, "\\");
- strcat(newpath, path);
- if (isdir)
- return !removedir(newpath);
- else if (!DeleteFileA(newpath)) {
- print_lasterror(newpath, GetLastError());
- return 1;
- }
- return 0;
- }
- int removedir(const char *path) {
- if (!iterpath(path, remove_iter, (void*)path))
- return 0;
- if (!RemoveDirectoryA(path)) {
- print_lasterror(path, GetLastError());
- return 0;
- }
- return 1;
- }
复制代码 |
|