代码改变世界

小记1

2014-01-15 19:52  jiaoluo  阅读(216)  评论(0编辑  收藏  举报

最近在学习文件操作,用到了_findfirst() 和_findnext() 两个函数,写了个小程序,输入一个目录名,输出它下面的文件和目录。

主要用到了这么几个CRT函数:

_access(); /*判断文件或文件夹路径是否合法*/

_chdir(); /*切换当前工作目录*/

_findfirst(); /*查找第一个符合要求的文件或目录*/

_findnext(); /*查找下一个*/

_findclose(); /*关闭查找*/

函数的详细信息请参照msdn。

代码如下:

  1. #include "io.h"  
  2. #include "direct.h"  
  3.   
  4. #include <iostream>  
  5. using std::cin;  
  6. using std::cout;  
  7. using std::endl;  
  8. using std::cerr;  
  9.   
  10.   
  11. #include <string>  
  12. using std::string;  
  13.   
  14.   
  15. int main()  
  16. {  
  17.     string dir;  
  18.     cout << "Input the name of directory: ";  
  19.     cin >> dir;  
  20.   
  21.     if (_access(dir.c_str(), 06) == -1)  
  22.     {  
  23.         cerr << "error: directory does not exist." << endl;  
  24.         exit(-1);  
  25.     }  
  26.   
  27.     if (dir.at(dir.length() - 1) != '\\')  
  28.     {  
  29.         dir += '\\';  
  30.     }  
  31.   
  32.     if (_chdir(dir.c_str()) != 0)  
  33.     {  
  34.         cerr << "error: function _chdir() failed.";  
  35.         exit(-1);  
  36.     }  
  37.   
  38.     _finddata_t fileinfo;  
  39.     memset(&fileinfo, 0x0, sizeof(fileinfo));     
  40.   
  41.       
  42.     intptr_t iFind = _findfirst("*", &fileinfo);  
  43.     if (iFind == -1)  
  44.     {  
  45.         cerr << "error: function _findfirst failed." << endl;  
  46.         exit(-1);  
  47.     }  
  48.   
  49.   
  50.     string filePath(dir + fileinfo.name);  
  51.   
  52.     cout << "name: " << filePath << endl;  
  53.   
  54.       
  55.     while (_findnext(iFind, &fileinfo) == 0)  
  56.     {  
  57.         filePath = dir + fileinfo.name;  
  58.         cout << "name: " << filePath << endl;  
  59.     }  
  60.   
  61.     _findclose(iFind);  
  62.   
  63.   
  64.     return 0;  
  65. }  

这是个简单的小程序,在vs2008下测试可以正常运行。 在这里提醒同样用到这几个函数的朋友,_findnext() 函数在成功时的返回值为0. 一般返回值为0,意思是为假,意味着失败。但CRT中很多函数在成功时返回0,类似的还有strcmp() 等。

我在首次使用时就犯了这个错误,意味_findnext() 成功时返回值 != 0,导致浪费了半天时间来Debug,后来仔细看msdn才纠正过来。