2017-02-11 87 views
0

這證明是非常困難的。我想使用stat來獲取最近修改的目錄的名稱。我對stat進行了相當多的研究,但我真的不知道如何使用它,所以我沒有任何代碼可以顯示。使用狀態獲取最近修改的目錄

如何在C中使用stat獲取最近修改的目錄?

+0

如何使用統計:http://unix.stackexchange.com/questions/240418/find-latest-files 在爲了在c中使用execl執行這個命令。 – Michael

+0

你的目錄列表是如何構建的?每個目錄的檢查時間都會有問題;如果您有一千個目錄,則可能會爲第一個目錄找到修改時間t1,並且您可能會在第n個目錄中找到一個修改時間tN,t1

回答

0

我假設你熟悉從給定目錄列出所有文件(並提取出目錄)[如果沒有在opendir/readdir上讀取]。算法將不準確,因爲目錄可能在其時間後被觸摸印方檢查,但假設這是不是一個問題,這裏的東西,你可能會做

DIR *dirp = opendir("."); 
    struct stat dStat; 
    time_t latest = 0; 
    while ((dp = readdir(dirp)) != NULL) { 
      memset(&dStat, 0, sizeof(dStat)); 
      if (stat(dp->d_name, &dStat) < 0) { 
        printf("Error getting info on file\n"); 
        continue; 
      } 
      // If not a directory skip 
      if ((dStat.st_mode & S_IFDIR) != S_IFDIR) { 
        continue; 
      } 
      // check with the latest timestamp 
      if (dStat.st_mtime > latest) { 
        // On finding a more recent file switch that to latest 
        strcpy(dName, dp->d_name); 
        latest = fStat.st_mtime; 
      } 
    } 
    closedir(dirp); 
    printf("Most recently touched directory %s\n", dName);