c - 如何在C程序中列出目录中的文件?

我正在尝试在 Linux 上编写一个 ftp 服务器。在这件事上,如何通过 C 程序列出终端目录中的文件?也许我可以使用 exec 函数来运行 find 命令,但我希望文件名作为字符串发送客户端程序。我该怎么做?

感谢您的回答。

最佳答案

一个适用于 POSIX 兼容系统的示例:

/*
 * This program displays the names of all files in the current directory.
 */

#include <dirent.h> 
#include <stdio.h> 

int main(void) {
  DIR *d;
  struct dirent *dir;
  d = opendir(".");
  if (d) {
    while ((dir = readdir(d)) != NULL) {
      printf("%s\n", dir->d_name);
    }
    closedir(d);
  }
  return(0);
}

请注意,这样的操作在 C 中依赖于平台。

来源:http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608

https://stackoverflow.com/questions/4204666/

相关文章:

linux - git中钩子(Hook)的符号链接(symbolic link)

python - 如何更改 seaborn 轴或图形级别图的图形大小

python - 如何从 Python 中的字典中提取所有值?

linux - 如何删除 CLOSE_WAIT 套接字连接

linux - VIM:如何在 Ubuntu 上精确到行

linux - 如何为长路径制作 "alias"?

python - functools partial 是如何做到的?

python - 理解 NumPy 的 einsum

c - 如何从 C 程序中获得 100% 的 CPU 使用率

python - 使用 url_for() 在 Flask 中创建动态 URL