2014-03-30 45 views
0

我需要打印当前目录中所有文件的名称。 但我必须做到这一点只与系统调用,所以我有SYS_OPEN, SYS_GETDENTS, SYS_READ等我在Ubuntu上工作。 我该怎么办? 我试图用这样的:从打印当前目录中所有文件的名称 - c

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; 
} 
+0

有关调用'ls'命令是什么? –

+1

我必须打印名称到标准输出(ls将帮助这里,你是正确的),但也成为一个文件..说明是使用SYS_GETDENTS,SYS_OPEN等..写一个c程序 – user3479031

+0

问题的名称是错误的。显然,这项任务不是打印出文件名列表。相反,它是一个练习系统调用的组合。 –

回答

-1

阅读opendir

手册页见http://linux.die.net/man/3/opendir

+0

谢谢,但他们让我们只包含“utils.h”,这意味着我们只有strlen,atoia和strcmp。所有其他的系统调用:SYS_OPEN,SYS_READ,SYS_CLOSE,SYS_GETDENTS,SYS_WRITE等。 – user3479031

+0

谁是“他们” - 我们在上次战争中纳粹分歧 –

+0

哈哈这门课程的学习者。 – user3479031

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;} 
} 
+0

尽管需要刷新缩进,你还是会得到+1 –

+0

谢谢,但他们让我们只包含“utils.h”,这意味着我们只有strlen,atoia和strcmp。所有其他的都是系统调用:SYS_OPEN,SYS_READ,SYS_CLOSE,SYS_GETDENTS,SYS_WRITE等。 – user3479031

+0

您当然可以使用系统调用重写代码。您也可以查看这里使用的函数的库代码,因为它肯定会在后台运行系统调用。 –

相关问题