首页 > 解决方案 > 在 POSIX 系统中使用 open() 和 read() 系统调用列出目录的文件

问题描述

我想知道如何做到这一点。我已经尝试了几件事,但似乎没有什么对我有用。我不想使用 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);

标签: clinuxoperating-systemsystemsystems-programming

解决方案


你不能这样做。内核只允许open使用具有特殊选项的目录,并且根本不允许read使用目录。您必须使用opendirreaddir

(在后台,使用我提到的那些特殊选项进行调用,并opendir调用私有系统调用。请参阅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。不建议自己这样做。)openreaddirgetdents


推荐阅读