首先,我在编程方面完全是新手,尤其是 C 语言。我要展示的示例是我从该站点获取的代码, 踢直到它没有完全达到我想要的效果。 :)
其次,我使用双核 Celeron 以及 Linux Mint 和 GNU C 编译器。
我想要做的是列出目录中的子目录,跳过父目录(如果有)。不幸的是,我的代码 不起作用。我尝试了 strcpy 和 strncpy,但我不知道如何使用它们,我只是搞砸了代码,这样我就得到了 当我尝试运行该程序时出现“段错误”。
代码如下:
/*
* This program displays the names of all files in the current directory.
*/
#include <dirent.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
DIR *d;
struct dirent *dir;
char dirname[255];
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
if (dir->d_type == DT_DIR)
{
strncpy(dirname, dir->d_name, 254);
dirname[254] = '\0';
if (dirname != "..") /* I want to skip this, but it doesn't work */
{
printf ("%s\n", dirname);
}
}
}
closedir(d);
}
return(0);
}
感谢您提供的任何帮助。我特别感兴趣的是那些可以提供教程的网站的链接,这些教程可以帮助我解决这个问题 小项目,因为我想更好地了解我到底在做什么。 :)
最佳答案
在 C 语言中,要比较字符串,您需要使用 strcmp
或 strncmp
。
if (strcmp(dirname, "..") != 0) { ... }
关于c - 在 GNU C 中列出时跳过目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33585298/