gpt4 book ai didi

c++ - 用于在整个文件系统中搜索文件的 POSIX 程序

转载 作者:太空狗 更新时间:2023-10-29 23:34:09 24 4
gpt4 key购买 nike

大家好。我需要编写一个 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;

}

最佳答案

POSIX.2 需要一个有效的“查找”命令。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: %s <filename>", argv[0]);
}

execlp("find", "find", "/", "-name", argv[1], "-print", (char *)NULL);
exit(EXIT_FAILURE);
}

关于c++ - 用于在整个文件系统中搜索文件的 POSIX 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5809476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com