LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1000|回复: 3

如何编程获得一个目录下的所有文件名?

[复制链接]
发表于 2006-8-14 08:27:34 | 显示全部楼层 |阅读模式
RT!
谢谢大虾的赐教!!
发表于 2006-8-14 11:16:05 | 显示全部楼层
opendir
回复 支持 反对

使用道具 举报

发表于 2006-8-14 15:10:04 | 显示全部楼层
ls 不就完了嘛
man popen
回复 支持 反对

使用道具 举报

发表于 2006-8-14 16:31:40 | 显示全部楼层
#include <stdio.h>

#include <dirent.h>

#include <alloca.h>

#include <string.h>

#include <stdlib.h>



void main(int argc, char *argv[])

{

   DIR *directory_pointer;  

   struct dirent *entry;

   struct FileList

   {

     char filename[64];

     struct FileList *next;

   } start, *node, *previous, *new;

   

   

   if ((directory_pointer = opendir(argv[1])) == NULL) /*取argv[1]文件夹的指针赋于*/

     printf("Error opening %s\n", argv[1]);

   else

     {

        start.next = NULL;

                /*将directory_pointer指向的文件名列表做成一个以FileList类型为结点的链*/

        while (entry = readdir(directory_pointer))/*读取directory_pointer指向的文件名*/

          {

            // Find the correct location

            previous = &start;

            node = start.next;

            while ((node) && (strcmp(entry, node->filename) > 0))/* 以字典序搜索在链表中此文件名应该插入的位置*/

             {

               node = node->next;

               previous = previous->next;

             }



            new = (struct FileList *)

                        malloc(sizeof(struct FileList));           

            if (new == NULL) /*内存分配失败*/

             {

               printf("Insufficient memory to store list\n");

               exit(1);

             }

            /*完成插入*/

                        new->next = node;

            previous->next = new;

            strcpy(new->filename, entry);

          }



        closedir(directory_pointer);

        node = start.next;

        /*输出整个链表结点的文件名*/

                while (node)

          {

            printf("%s\n", node->filename);

            node = node->next;

          }

     }

     printf(" Press any key to quit...");

     getch();

     return;

}



应该可以实现
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表