问题描述如下,这是一个可选的介绍
有两个函数,第一个接收带有文件位置的字符串,第二个接收该位置的所有文件(我不确定这些函数是否有问题,但为了清楚起见,我仍然会插入他们)
char *fun_get_cur_path(void){
char *buf = malloc(sizeof (char) * BUF_PATH);
if( getcwd(buf, BUF_PATH) == NULL){
if(errno == ERANGE){
printf("Buffer is small\n");
exit(EXIT_FAILURE);
}
perror("Can't get current dir");
exit(EXIT_FAILURE);
}
// printf("\n");
return buf;
}
int list_in_dir(const char *path, struct dirent **new_entry)
{
struct dirent *entry;
DIR *dir;
int i = 0;
dir = opendir(path);
if (dir == NULL) {
printf("Can't open path: %s\n", path);
exit(EXIT_FAILURE);
}
while ( (entry = readdir(dir)) != NULL) {
if( !strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
continue;
new_entry[i++] = entry;
}
closedir(dir);
return i;
}
嗯,有主要
int main(){
char *buf_path = NULL;
struct dirent *entry[COUNT_OF_FILES];
int count_of_entry_files = 0;
buf_path = fun_get_cur_path();
count_of_entry_files = list_in_dir(buf_path, entry);
printf("---------------------------------------------------------------------------\n");
printf("FILES\n\n");
for(int i = 0; i < count_of_entry_files; i++)
printf("%s\n", entry[i]->d_name);
printf("\n");
}
实际问题是什么:当我运行此代码时,显示以下内容:
--------------------------------------------------------------------------
FILES
-------
eg
test
main.o
Makefile
testing.txt
Press <RETURN> to close this window...
它应该输出以下内容
--------------------------------------------------------------------------
FILES
ASCII.jpeg
test
main.o
Makefile
testing.txt
Press <RETURN> to close this window...
也就是说,zanks-----替换了文件名。如果我禁用缓冲stdout,那么一切正常。或者,如果我添加printf("\n")到函数的末尾fun_get_cur_path(),那么它似乎也可以工作(但在我看来,这是暂时的,直到我增加字符数-----)。
可能是什么问题呢?
阅读文档
readdir还
您不能存储由
readdir. 返回的指针指向的数据可能会被下一次调用销毁readdir。然后closedir这些指针完全消失了。