我的代码中有以下内容:(用C编写)
ftw(argv[2], parseFile, 100)
argv[2]是本地目录路径。例如。argv[2]=“testcases”,并且在与my.o文件相同的目录中有一个testcases文件夹。
我的理解是,这应该遍历目录testcases并将找到的每个文件发送到函数parsefile。
实际上,它只是将我的参数发送到函数parsefile,仅此而已。我做错什么了?我该如何正确使用它?
编辑:这是解析文件:
int parseFile(const char * ftw_filePath,const struct stat * ptr, int flags){
FILE * file;
TokenizerT * currFile;
char fileString[1000], * currWord, * fileName;
fileName = strdup(ftw_filePath);
if( fileName == NULL || strlen(fileName) <= 0){
free(fileName);
return -1;
}
printf("\n%s\n",fileName);
if(strcmp(fileName,"-h")== 0){
printf("To run this program(wordstats) type './wordstat.c' followed by a space followed by the file's directory location. (e.g. Desktop/CS211/Assignment1/test.txt )");
free(fileName);
return 1;
}
else{
file=fopen(fileName,"r");
}
if(!file){
fprintf(stderr,"Error: File Does not Exist in designated location. Please restart the program and try again.\n");
free(fileName);
return 0;
}
memset(fileString, '\0', 1000);
while(fscanf(file,"%s", fileString) != EOF){ /* traverses the file line by line*/
stringToLower(fileString);
currFile = TKCreate("alphanum",fileString);
while((currWord = TKGetNextToken(currFile)) != NULL) {
insert_List(currWord, words,fileName);
}
free(currFile->delimiters);
free(currFile->copied_string);
free(currFile);
memset(fileString, '\0', 1000);
}
fclose(file);
free(fileName);
return 1;
}
如果我为我的argv[2]输入testcases/big.txt,它将起作用,但如果我放置testcases,它将不起作用
最佳答案
如man page中所述,来自ftw正在调用的函数的非零返回值告诉ftw停止运行。
您的代码有各种返回语句,但唯一返回0的是错误条件。
关于c - 在C中正确使用ftw(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19508835/