c - 在 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);
解决方案
你不能这样做。内核只允许open
使用具有特殊选项的目录,并且根本不允许read
使用目录。您必须使用opendir
和readdir
。
(在后台,使用我提到的那些特殊选项进行调用,并opendir
调用私有系统调用。请参阅https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/ linux/opendir.c和https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/readdir.c。不建议自己这样做。)open
readdir
getdents
推荐阅读
- python - 在 Pandas 中,如何对特定的连续列进行一些算术计算
- google-apps-script - 如何从文档中获取评论和回复列表并将内容添加到工作表中?
- visual-studio - 如何使用 Visual Studio 测试资源管理器从 DynamicData 运行一项特定测试?
- c# - 当 Oracle 存储过程仅返回 -1 时对其进行故障排除
- python - 将具有多个值的熊猫数据框列字符串拆分为单独的行
- html - 如何显示所有名称?
- sql - 消息 7202,级别 11,状态 2,第 1 行在 sys.servers 中找不到服务器“acct”
- google-apps-script - 谷歌表格,两种字体大小一个单元格
- swift - 如何快速获取两个 UICollectionView 的 ScrollView?
- nginx - nginx 反向代理 - 如何为多个应用程序提供服务