嘿大家。我需要編寫一個POSIX程序來搜索整個文件系統,以查找從頂層目錄開始的指定文件。我有一些根本沒有完成的代碼,但是當我運行它並檢查某個特定文件是否是一個目錄時,它說這個文件根本不是一個目錄,而是正在嘗試進入它,導致錯誤。我不知道我可以告訴它,這種類型的文件不是一個目錄。POSIX程序搜索整個文件系統的文件
這是我的代碼。我知道這並不完美,我可能會在獲取目錄名稱並將它們傳遞給函數的過程中做一些不同的事情。無論哪種方式,我非常肯定我必須遞歸地做到這一點。
有問題的文件是/ dev/dri/card0,我從Debian虛擬機運行此文件。
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <stdint.h>
#include <locale.h>
#include <langinfo.h>
#include <fcntl.h>
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
void SearchDirectory(string file_Name, string directory){
string new_Directory = directory;
DIR *dirp;
dirp = opendir(directory.c_str());
struct dirent *dptr;
struct stat statStruct;
while(dptr = readdir(dirp)){
stat(dptr->d_name, &statStruct);
if(S_ISDIR(statStruct.st_mode)){
string check = dptr->d_name;
if (check.compare(".") == 0 || check.compare("..") == 0){
continue;
}
else{
cout << dptr->d_name << " is is a directory" << endl;
new_Directory.append("/");
new_Directory.append(dptr->d_name);
SearchDirectory(file_Name, new_Directory);
}
}
else if(S_ISREG(statStruct.st_mode)){
string check = dptr->d_name;
if(check.compare(file_Name) == 0){
cout << "Found " << file_Name << " in " << directory << "/" << endl;
}
}
}
}
int main(int argc, char *argv[]){
if(argc < 2 || argc > 2){
cerr << "This program will find the specified file." << endl;
cerr << "Usage: mysearch <filename>" << endl;
return 1;
}
string file_Name = argv[1];
SearchDirectory(file_Name, "/");
return 0;
}
btw,'find/-name card0' – ikegami 2011-04-27 19:32:07
此外,[nftw](http://pubs.opengroup.org/onlinepubs/9699919799/functions/nftw.html),雖然這是XSI而不是POSIX基礎。 – Random832 2011-04-27 19:39:20
@ikegami - 我不認爲他在尋找card0。我認爲他意味着/ dev/dri/card0的S_ISDIR爲true,但是opendir(「/ dev/dri/card0」)失敗。 – 2011-04-27 21:08:00