如何确定目录或在C Linux中的文件 [英] how to determine directory or file in linux in c
问题描述
我想不打印目录名中只打印文件名。所以,我实现这个功能。
I want to print only file names without printing Directory Names. So, I implement this function
void list_file(char* directory){
DIR *d;
struct dirent *dir;
d = opendir(directory);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%c", dir->d_name[(int)strlen(dir->d_name)]);
if(dir->d_name[(int)strlen(dir->d_name)-2] != '/')
printf("%s\n", dir->d_name);
}
closedir(d);
}
}
我检查目录名以/字符结束。所以,我检查,如果有在名称末尾/字符,不打印的名字,但是当我运行的功能,所有的人都在所选目录印刷?
I checked that Directory names ends with '/' character. So, I checked that if there are '/' character at the end of name, don't print that name but when I run the function, all of them is printed in selected directory?
您可以带领我,我怎么能检查目录名的末尾?
Can you lead me that how can I check the end of Directory name?
推荐答案
您要找的是 统计
或其变体之一。具体看 struct stat中
的 ST_MODE
字段。你感兴趣的宏 S_ISDIR(X)
。
What you are looking for is stat
or one of its variants. Specifically look at the st_mode
field of struct stat
. The macro you are interested in is S_ISDIR(x)
.
在下面找到您修改code演示你想要什么:
Find below your modified code that demonstrates what you want:
void list_file(char* directory) {
DIR *d;
struct dirent *dir;
int dir_len = strlen(directory);
char* path = malloc(dir_len + NAME_MAX + 2); // +2, 1 for '/' and 1 for '\0'
if(path == NULL) {
fprintf(stderr, "malloc failed\n");
return;
}
strcpy(path, directory);
if(path[dir_len-1] != '/') {
path[dir_len] = '/';
dir_len++;
}
d = opendir(directory);
if (d) {
while ((dir = readdir(d)) != NULL)
{
struct stat buf;
strcpy(&path[dir_len], dir->d_name);
if(stat(path, &buf) < 0) {
fprintf(stderr, "error\n");
}
else {if(!S_ISDIR(buf.st_mode)) {
printf("%s\n", dir->d_name);
}
}
}
closedir(d);
}
free(path);
}
我已删除,因为它是打印字符串的空终止字符的第一个打印。
I have removed your first print as it was printing the null terminating character of the string.
更新:
由于在评论中指出,因为我们正在处理的Linux,你可以使用结构的dirent
的 d_type
字段(这是不 POSIX 的的一部分,但是<一部分HREF =http://man7.org/linux/man-pages/man3/readdir.3.html相对=nofollow> Linux的)。
As pointed out in the comments since we are dealing with Linux you can use the d_type
field in struct dirent
(which is not part of POSIX but is part of Linux).
随着中说的code将是如下。
With that said the code would be the following.
void list_file(char* directory){
DIR *d;
struct dirent *dir;
d = opendir(directory);
if (d) {
while ((dir = readdir(d)) != NULL)
{
struct stat buf;
if(dir->d_type & DT_DIR) {
printf("%s\n", dir->d_name);
}
}
closedir(d);
}
}
这是很多清洁,没有必要的malloc
。
这篇关于如何确定目录或在C Linux中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!