gpt4 book ai didi

C 列出其他目录中的目录名称

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:31 25 4
gpt4 key购买 nike

我正在编写一个列出目录名称的程序。这不是一个非常复杂的代码,但是在我启动我的程序后我得到了奇怪的错误

#include <dirent.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>


int main() {
struct dirent * dir;
struct stat buf;
DIR *d;
if(d = opendir("/..."))
{
while(dir = readdir(d))
{
if(S_ISDIR(buf.st_mode))
puts(dir->d_name);
closedir(d);
}
}
else
perror("read");
return 0;
}

我得到的输出是

*** Error in `./names.exe': double free or corruption (top): 0x00000000011d3010 ***
======= Backtrace: =========
/lib64/libc.so.6(+0x81499)[0x7f702b1bc499]
/lib64/libc.so.6(closedir+0xd)[0x7f702b1fbaed]
./names.exe[0x40068d]
/lib64/libc.so.6(__libc_start_main+0xf5)[0x7f702b15d445]
./names.exe[0x400579]
======= Memory map: ========

我做错了什么?

最佳答案

您在读取目录流的过程中关闭了目录流。变化:

while(dir = readdir(d))
{
if(S_ISDIR(buf.st_mode))
puts(dir->d_name);
closedir(d);
}

到:

while(dir = readdir(d))
{
if(S_ISDIR(buf.st_mode))
puts(dir->d_name);
}
closedir(d);

这样你就不会关闭它,直到你完成它。

关于C 列出其他目录中的目录名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56709423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com