如何在C程序中列出目录中的文件? [英] How to list files in a directory in a C program?

查看:21
本文介绍了如何在C程序中列出目录中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write an ftp server on Linux. In this matter how can I list files in the directory on terminal by a C program? Maybe I can use exec function to run find command but I want file name as a string to send client program. How can I do this?

感谢您的回答.

推荐答案

一个例子,适用于 POSIX 兼容系统:

An example, available for POSIX compliant systems :

/*
 * 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
", dir->d_name);
    }
    closedir(d);
  }
  return(0);
}

请注意,这样的操作在 C 中是平台相关的.

Beware that such an operation is platform dependant in C.

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

这篇关于如何在C程序中列出目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆