[英]while loop and if not getting along with readdir() in C
在嘗試編寫一個程序來搜索目錄並列出與命令行參數匹配的內容時,我遇到了一個似乎無法弄清的問題。
我在while循環中放入了if語句,以檢查字符串是否匹配,但是問題是我只得到目錄中的最后一個條目。 如果我注釋掉if語句,它會很好地打印整個目錄,並且它與字符串匹配也很好,但是不會兩者都做。
一位朋友建議它與堆棧有關,但是由於每次讀取后都在打印,所以我不知道為什么會這樣。
DIR *dirPos;
struct dirent * entry;
struct stat st;
char *pattern = argv[argc-1];
//----------------------
//a few error checks for command line and file opening
//----------------------
//Open directory
if ((dirPos = opendir(".")) == NULL){
//error message if null
}
//Print entry
while ((entry = readdir(dirPos)) != NULL){
if (!strcmp(entry->d_name, pattern)){
stat(entry->d_name, &st);
printf("%s\t%d\n", entry->d_name, st.st_size);
}
}
entry
必須定義為指針。 struct dirent* entry
。 我在c上編譯了它,並且工作正常。
#include <dirent.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
int main( int argc, char **argv )
{
DIR *dirPos;
struct dirent* entry;
struct stat st;
char *pattern = argv[argc-1];
//----------------------
//a few error checks for command line and file opening
//----------------------
//Open directory
if ((dirPos = opendir(".")) == NULL){
//error message if null
}
//Print entry
while ((entry = readdir(dirPos)) != NULL){
if (!strcmp(entry->d_name, pattern)){
stat(entry->d_name, &st);
printf("%s\t%d\n", entry->d_name, st.st_size);
}
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.