打印当前目录中所有文件的名称 - c

时间:2014-03-30 20:38:27

标签: c

我需要打印当前目录中所有文件的名称。 但我必须只使用系统调用,所以我有SYS_OPEN, SYS_GETDENTS, SYS_READ等我正在研究Ubuntu。 我该怎么做? 我试着用这个:

system_call(SYS_OPEN, ".", 0, 0777);

然后转到READ并写信给STDOUT ..但它不起作用。

**我无法使用标准库。 谢谢!

编辑: 示例代码: **程序集中有一个文件,具有执行调用的“系统调用”功能。     #include“util.h”

#define SYS_WRITE 4

#define SYS_OPEN 5

#define SYS_CLOSE 6

#define SYS_READ 3

#define SYS_LSEEK 19

#define SYS_GETDENTS 141

#define BUF_SIZE 1024

#define STDOUT 1

 struct linux_dirent {
           long           d_ino;
           int         d_off;

           unsigned short d_reclen;

           char           d_name[];

       };         

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

{

   int fd=0;

   int nread;

   char * nread_str;

   char buf[BUF_SIZE];

   struct linux_dirent *d;

           int bpos;

           char d_type;

  fd=system_call(SYS_OPEN,".", 0 , 0);
          for ( ; ; ) {

               nread = system_call(SYS_GETDENTS, fd, buf, BUF_SIZE);

               if (nread == -1)              

        system_call(SYS_WRITE,STDOUT, "error-getdents",BUF_SIZE);

               if (nread == 0)

                   break;

          system_call(SYS_WRITE,STDOUT, "--------------- nread=%d ---------------\n",100);

      nread_str=itoa(nread);      

          system_call(SYS_WRITE,STDOUT, nread_str,100);                      

          system_call(SYS_WRITE,STDOUT, "i-node#  file type  d_reclen  d_off   d_name\n",100);

               for (bpos = 0; bpos < nread;) {

                   d = (struct linux_dirent *) (buf + bpos);

                  /* printf("%8ld  ", d->d_ino);**/

                   d_type = *(buf + bpos + d->d_reclen - 1);


                  /* printf("%4d %10lld  %s\n", d->d_reclen,
                           (long long) d->d_off, (char *) d->d_name);**/
                   bpos += d->d_reclen;
               }
           }

}
  return 0;
}

2 个答案:

答案 0 :(得分:3)

#include <fstream>
#include <iostream>
#include <string>

#include <dirent.h>

using namespace std;

int main()
  {
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\")) != NULL) {
  /* print all the files and directories within directory */
  while ((ent = readdir (dir)) != NULL) {
    printf ("%s\n", ent->d_name);
  }
  closedir (dir);
} else {
  /* could not open directory */
  perror ("");
  return EXIT_FAILURE;}
}

答案 1 :(得分:-1)

阅读opendir等手册页

请参阅http://linux.die.net/man/3/opendir