最近在做一个linux下c程序到windows下的移植工程,在移植过程中发现windows下对opendir readdir存在很大问题,经多方查找,终于在http://www.tenouk.com/cpluscodesnippet/viewtopic.php?t=670上找到了解决办法,利用_chdir,_findfist,_findnext函数,很轻松的完成了移植工作。
现把上面链接的程序贴过来,
To show: Using _chdir(), ctime()/ctime_s(), _findfirst(), _findnext(), _findclose()
Code: |
/* The use of the 32-bit _find functions to print a list of all files (and their attributes) in the current directory. */ /* Don't forget to put the .h extension to the header files */ #include <stdio> #include <stdlib> #include <io> #include <time> #include <direct> #include <conio> #include <ctype> #define SIZE 50 int main() { // char path[50] = "C://WINNT//System32//config"; - Windows 2000 char path[50] = "C://Windows//System32//config"; struct _finddata_t c_file; intptr_t hFile; char buf[SIZE]; printf("Change to %s/n", path); if(_chdir(path)) { printf("Unable to locate the directory: %s/n", path); exit(1); } else /* Find first in the current directory */ hFile = _findfirst("*.*", &c_file); /* List the files... */ printf("Listing of files in the directory %s/n/n", path); printf("/nRDO HID SYS ARC FILE DATE %20c SIZE/n", ' '); printf("--- --- --- --- ---- ---- %20c ----/n", ' '); printf((c_file.attrib & _A_RDONLY) ? " Y " : " N "); printf((c_file.attrib & _A_SYSTEM) ? " Y " : " N "); printf((c_file.attrib & _A_HIDDEN) ? " Y " : " N "); printf((c_file.attrib & _A_ARCH) ? " Y " : " N "); // unsafe version is ctime() ctime_s(buf, SIZE, &(c_file.time_write)); printf(" %-30s %.20s %9ld/n", c_file.name, buf, c_file.size); /* Find the rest of the files */ while(_findnext(hFile, &c_file) == 0) { printf((c_file.attrib & _A_RDONLY) ? " Y " : " N "); printf((c_file.attrib & _A_SYSTEM) ? " Y " : " N "); printf((c_file.attrib & _A_HIDDEN) ? " Y " : " N "); printf((c_file.attrib & _A_ARCH) ? " Y " : " N "); // unsafe version is ctime() ctime_s(buf, SIZE, &(c_file.time_write)); printf(" %-30s %.20s %9ld/n", c_file.name, buf, c_file.size); } _findclose(hFile); return 0; } |