【问题标题】:Listing directory's files using open() and read() syscalls in POSIX systems在 POSIX 系统中使用 open() 和 read() 系统调用列出目录的文件
【发布时间】:2021-06-21 11:00:32
【问题描述】:

我想知道如何做到这一点。我已经尝试了几件事,但似乎没有什么对我有用。我不想使用 opendir() 系统调用,也不想使用 readdir() 系统调用。你能告诉我怎么做吗,因为我得到了垃圾值。我想列出文件夹内的文件。我从这段代码中得到了存储在缓冲区中的垃圾值。

char buffer[16];
    size_t offset = 0;
    size_t bytes_read;
    
    int i;
    /* Open the file for reading. */
    int fd = open ("testfolder", O_RDONLY);
    /* Read from the file, one chunk at a time. Continue until read
    “comes up short”, that is, reads less than we asked for.
    This indicates that we’ve hit the end of the file. */
    do {
        /* Read the next line’s worth of bytes. */
        bytes_read = read (fd, buffer, 16);
        /* Print the offset in the file, followed by the bytes themselves.*/
        
        // printf ("0x%06lx : ", offset);
        // for (i = 0; i < bytes_read; ++i)
        // printf ("%02x ", buffer[i]);
        printf("%s", buffer);
        printf ("\n");
        /* Keep count of our position in the file. */
        // offset += bytes_read;
    }
    while (bytes_read!=-1);

【问题讨论】:

    标签: c linux operating-system system systems-programming


    【解决方案1】:

    你不能这样做。内核只允许open 出现在带有特殊选项的目录上,它根本不允许read 出现在一个目录上。您必须使用opendirreaddir

    (在后台,opendir 使用我提到的那些特殊选项调用 openreaddir 调用私有系统调用 getdents。请参阅 https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/opendir.chttps://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/readdir.c。不建议您自己这样做.)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-11
      • 2019-05-10
      • 2011-02-04
      • 2013-11-27
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多