c - Char ** 在递归添加时不断被覆盖
问题描述
我的代码应该将文件放在目录中,将它们放入字符串数组中,然后打印内容。目前在我的 Functions.c 文件中,它成功写入了正确的数组索引,但是当我写入下一个数组索引时被覆盖。任何帮助表示赞赏。
主程序
#include "Headers.h"
void main(){
listFiles("C:/Users/me/Documents/testDoc");
//printf("%s",fileArray[0]);
printf("End");
return;
}
函数.c
#include "Headers.h"
void listFiles(const char *foldername){
struct dirent *dp; //creates object of struct dirent
DIR *dir=opendir(foldername); //creates object of directory
char **fileArray=(char **)calloc(1,sizeof(char *));
if (!dir) //checks to see if directory exsists
return;
int numloops=1;
while ((dp = readdir(dir)) != NULL)//recursivley goes through list
{
printf("%d\n",numloops);
if(numloops==1){
fileArray[0]=dp->d_name; //maps first file to position zero
printf("%s test\n",fileArray[0]);
}
else{
fileArray=realloc(fileArray,numloops*sizeof(char *));
fileArray[numloops-1]=dp->d_name; //maps next file in order to position -1 to make enough memory since array starts at 0
printf("%s test\n",fileArray[numloops-1]);
}
numloops++;
printf("%s original\n", dp->d_name);//maps d_name recursivley
}
// Close directory stream
printf("Value at index 2 %s\n",fileArray[2]);
printf("Value at index 3 %s\n",fileArray[3]);
closedir(dir);
return;
}
头文件.h
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
void listFiles(const char *foldername);
输出
1
. test
. original
2
.. test
.. original
3
Doc 1.txt test
Doc 1.txt original
4
Doc 2.txt test
Doc 2.txt original
5
Doc 3.txt test
Doc 3.txt original
Value at index 2 Doc 3.txt
Value at index 3 Doc 3.txt
End
预期产出
1
. test
. original
2
.. test
.. original
3
Doc 1.txt test
Doc 1.txt original
4
Doc 2.txt test
Doc 2.txt original
5
Doc 3.txt test
Doc 3.txt original
Value at index 2 Doc 1.txt
Value at index 3 Doc 2.txt
End
解决方案
返回的指针和结构中的指针可能会失效,或者结构或存储区域可能会被
readdir()
对同一目录流的后续调用覆盖。
那句话的意思是readdir
可以一遍又一遍地返回指向同一结构的指针,这意味着d_name
成员每次都是相同的。
所以当你这样做时
fileArray[numloops-1]=dp->d_name;
您使数组中的所有元素都指向完全相同的内存。
解决方案是复制字符串d_name
,例如
fileArray[numloops-1]=strdup(dp->d_name);
当然,一旦你完成了,你需要free
数组中的每一个字符串。
推荐阅读
- java - java中RPC风格和文档风格JAX-WS Web服务的主要区别
- javascript - Webpack如何导入整个文件
- python - 定义 ansible vars dict,其中变量 B 包括来自同一个 dict 的变量 A
- javascript - DataTables jQuery 插件:与 vue.js 混合时禁用排序和分页
- python-3.x - Tensorflow 中 hstack 和 vstack 的对应物
- node.js - 如何避免使用角度的重复文档
- java - javac 命令仅在我在用户文件夹中打开 CMD 时可用
- node.js - 寻找更新 AWS 凭证的更好方法
- kivy - Kivy TextInput 文本溢出。TextInput 视口外的光标
- javascript - CefSharp (chromium) javascript 增加内存限制