我正在编写这个脚本来枚举目录中的每个文件来练习使用指针,因为我对这个概念和 C 语言都很陌生。由于某种原因, **getFiles() 的 return 语句返回为空。奇怪的是,在 getFiles() 函数中,当我打印“字符串数组”(目录)时,它会打印目录中 3 个文件中的 1 个。但是,当我在 main() 中打印结果时,没有任何反应。
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main(){
char **getFiles();
printf("\nFUNCTION RETURN:\n%s", *getFiles());
return 0;
}
#define BUFFER_SIZE 4096
char **getFiles(){
char **dirs;
int total = 10; //Need to do this
dirs = malloc(total*sizeof(char *));
char buffer[BUFFER_SIZE];
struct dirent *de;
DIR *dr = opendir(".");
if (dr == NULL)
{
printf("Error");
return 0;
}
int x=0;
while ((de = readdir(dr)) != NULL){
int length = strlen(de->d_name);
dirs[x] = malloc(length*sizeof(char));
strcpy(buffer, de->d_name);
strcpy(dirs[x], buffer);
dirs[x] = buffer;
x++;
}
closedir(dr);
printf("\nPRINT DIRS\n:\n%s", *dirs);
return dirs;
for(int i =0; i<x;i++){
free(dirs[i]);
}
free(dirs);
}
正如我所说,我对整个指针和地址仍然很陌生,所以我尝试取消引用一堆东西并打印它们,但没有任何帮助。
我的兄弟,我正在读书。
第一:
char **getFiles();
这根本没有意义。 变量名在哪里???
char **my_files = getFiles();
这是实现这一点的好方法。
int length = strlen(de->d_name);
dirs[x] = malloc(length*sizeof(char));
strcpy(buffer, de->d_name);
strcpy(dirs[x], buffer);
dirs[x] = buffer;
为什么不直接使用
strdup()
?
return dirs;
for(int i =0; i<x;i++){
free(dirs[i]);
}
free(dirs);
return
之后的所有代码都不会被执行。
这里有一些可以帮助你的东西: GNU C语言介绍及参考手册
这里有一些东西......(希望你不要使用它,如果你不明白它):
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#define TOTAL_DIR 10
char **
getFiles(void)
{
char **dirs;
struct dirent *de;
DIR *dr;
dr = opendir(".");
if (dr == NULL)
{
printf("Error\n");
return (0);
}
dirs = calloc(TOTAL_DIR, sizeof(char *));
if (dirs == NULL)
{
printf("Error\n");
return (0);
}
int x = 0;
de = readdir(dr);
while (de != NULL)
{
dirs[x] = strdup(de->d_name);
x++;
de = readdir(dr);
}
closedir(dr);
return (dirs);
}
int
main(void)
{
char **files;
files = getFiles();
printf("Files : \n");
for (int i = 0; i < TOTAL_DIR; i++)
{
if (files[i] != NULL)
printf("%s\n", files[i]);
free(files[i]);
}
free(files);
return (0);
}