[英]Checking whether path is a file or directory
我剛剛開始學習C並且正在嘗試進行路徑列表。 我試圖使用dirent
列出目錄中的路徑,並嘗試使用stat
檢查結果是文件還是目錄。 但是,即使路徑是文件,它也會將每個路徑作為目錄返回。
這是我的代碼:
[編輯]
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
int main(void)
{
DIR *mydir = opendir("/Library/Logs");
char path[250];
struct dirent *entry = NULL;
struct stat buf;
while((entry = readdir(mydir))) /* If we get EOF, the expression is 0 and
* the loop stops. */
{
snprintf(path, 250, "%s",entry->d_name);
stat(path,&buf);
if(S_ISDIR(buf.st_mode))
printf("D: %s\n", path);
else if (S_ISREG(buf.st_mode))
printf("F: %s\n", path);
else
printf("O: %s\n", path);
}
}
stat(entry->d_name,&buf);
此時,您沒有關於您正在查找的目錄的任何上下文。
您需要創建一個緩沖區,並在調用stat
之前連接directory
/ filename
(使用strcat
或snprintf
)
檢查對stat
的返回值的調用 - 如果非零,請查看errno
以查看出錯的地方。 我猜它現在正在報告ENOENT。
嘗試使用readdir和dirent
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
/* "readdir" etc. are defined here. */
#include <dirent.h>
/* limits.h defines "PATH_MAX". */
#include <limits.h>
/* List the files in "dir_name". */
static void
list_dir (const char * dir_name)
{
DIR * d;
/* Open the directory specified by "dir_name". */
d = opendir (dir_name);
/* Check it was opened. */
if (! d) {
fprintf (stderr, "Cannot open directory '%s': %s\n",
dir_name, strerror (errno));
exit (EXIT_FAILURE);
}
while (1) {
struct dirent * entry;
const char * d_name;
/* "Readdir" gets subsequent entries from "d". */
entry = readdir (d);
if (! entry) {
/* There are no more entries in this directory, so break
out of the while loop. */
break;
}
d_name = entry->d_name;
/* Print the name of the file and directory. */
printf ("%s/%s\n", dir_name, d_name);
/* See if "entry" is a subdirectory of "d". */
if (entry->d_type & DT_DIR) {
/* Check that the directory is not "d" or d's parent. */
if (strcmp (d_name, "..") != 0 &&
strcmp (d_name, ".") != 0) {
int path_length;
char path[PATH_MAX];
path_length = snprintf (path, PATH_MAX,
"%s/%s", dir_name, d_name);
printf ("%s\n", path);
if (path_length >= PATH_MAX) {
fprintf (stderr, "Path length has got too long.\n");
exit (EXIT_FAILURE);
}
/* Recursively call "list_dir" with the new path. */
list_dir (path);
}
}
}
/* After going through all the entries, close the directory. */
if (closedir (d)) {
fprintf (stderr, "Could not close '%s': %s\n",
dir_name, strerror (errno));
exit (EXIT_FAILURE);
}
}
int main ()
{
list_dir ("/Library/Logs");
return 0;
}
輸出將是
/Library/Logs/.<br />
/Library/Logs/..<br />
/Library/Logs/somedir001<br />
/Library/Logs/somedir002
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.