C语言 如何为仅从目录中打印出特定类型文件的条件设计 IF 语句?(在正文中解释更多)



截至目前,如果您删除 IF 语句if(strncmp(strup(buff,len) + len - 4, ".txt", 4) == 0)代码将打印出我当前目录中的所有文件以及当前目录中的目录等。但是我想设计一个 IF 语句,以便我只打印出我选择的文件,在下面的示例中,我试图让它只打印出".txt",但话虽如此,我似乎无法弄清楚如何正确设计我的条件语句。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define sizeFileName 500
#define filesMax 5000
int main( int argc, char ** argv) {
FILE * fp = popen( "find . -type f", "r");
char buff[sizeFilesName];
int nFiles = 0;
char * files[filesMax];
while(fgets(buff,sizeFileName,fp)) {
int len = strlen(buff) - 1;
if(strncmp(strup(buff,len) + len - 4, ".txt", 4) == 0){
files[nFiles] = strndup(buff,len);
printf("t%sn", files[nFiles]);
nFiles ++;
}
}
fclose(fp);
printf("Found %d files:n", nFiles);
// clean up
for(int i = 0; i < nFiles ; i ++ ) {
free(files[i]);
}
return 0;
}

旁注:基本上我的想法是,我相信一些字符持有一个大路径名,说"文件夹/文件夹/文件夹/文件.txt",基本上,如果我可以比较文件".txt"和".txt",因此它将被接受并打印到控制台中。

您没有从字符串的正确偏移量开始。 您要检查最后 4 个字符,因此请从偏移量strlen(buf) - 4开始。

int len = strlen(buff);
if (strncmp(buff + len - 4, ".txt", 4) == 0) {

最新更新