2014-12-31 205 views
0

我正在做一個代碼,它獲取的文件夾中的文件夾的目錄,然後它打印出所有的txt文件與創建/最後修改的月份相同。如何使用c中的目錄打印修改月份相同的文件?

例如,如果用戶鍵入'JANUARY',程序將打印出1月份創建/上次修改的所有文件的名稱。

這是我的代碼,但它不起作用。

DIR *da; 
struct dirent *ep; 
struct stat attrib; 

da = opendir ("./"); 
if (da != NULL) 
{ 
    while (ep = readdir (da)) 
    { 
    while ((ep = readdir (da)) != NULL) 
    { 
     const size_t len = strlen(ep->d_name);  

      if (len > 4     && 
      ep->d_name[len - 4] == '.' && 
      ep->d_name[len - 3] == 'T' && 
      ep->d_name[len - 2] == 'X' && 
      ep->d_name[len - 1] == 'T') { 

       stat(ep->d_name, &attrib); 

       strftime(month, MAX_SIZE, "%m", localtime(&(attrib.st_ctime))); 

       comp = strcmp(month,input); 
       if(comp == 0) { 
        printf ("%s\n", ep->d_name); 
       } 
      } 
     } 
    closedir (da); 
    }  
} 
+0

編譯所有警告和調試信息('gcc -Wall -Wextra -g')。然後**使用調試器**('gdb') –

+0

您正在收到哪個錯誤? –

+0

'(void)closedir(da);'中的'(void)'的_use_是什麼? –

回答

2

你在錯誤的地方關閉目錄流。你正在關閉內部,但你必須在外部時間後關閉它。

if (da != NULL) 
{ 
while (ep = readdir (da)) 
    while ((ep = readdir (da)) != NULL) 
    { 
    const size_t len = strlen(ep->d_name); 

    if (len > 4     && 
     ep->d_name[len - 4] == '.' && 
     ep->d_name[len - 3] == 't' && 
     ep->d_name[len - 2] == 'x' && 
     ep->d_name[len - 1] == 't') { 

      stat(ep->d_name, &attrib); 
      foo = localtime(&(attrib.st_mtime)); 

      if(foo->tm_mon+1 == 1) { 


      printf ("%s\n", ep->d_name); 
       } 
     } 
    } 
closedir (da); 
} 

之後,檢查條件,如果你可以使用strcmp函數。

int strcmp(const char *s1, const char *s2); 

if (strcmp(ep->d_name+(len-4),".txt") ==0){ 
... 
} 
+0

哇,非常感謝!你真的救了我! – AmperSand

+0

@AmpperSand沒問題! –

相關問題