C - 字数组不断被覆盖

C - word array keeps getting overridden

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

// This program is going to scan all files in the current directory. It will make a tree for every folder
// and the folder will have a subsection of files in the tree format. YES SORTING!

char **word;
int coun = 0;

void printdir(char *dir, int depth)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;

    if ((dp = opendir(dir)) == NULL) 
    {
        fprintf(stderr,"cannot open directory: %s\n", dir);
        return;
    }
    
    chdir(dir);
    
    while((entry = readdir(dp)) != NULL) 
    {
        lstat(entry->d_name,&statbuf);
        
        if (S_ISDIR(statbuf.st_mode)) // Check if it's a directory
        {
            /* Found a directory, but ignore . and .. */
            if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)
            {
                continue;
            }

            word[coun] = ("%s", entry->d_name); // Put the file name in the array.
            coun++;
            printf("- %*s%s\n", depth, "", entry->d_name); // Print the name of the dir entry.
            /* Recurse at a new indent level */
            printdir(entry->d_name, depth + 1);
        }
        else 
        {
            word[coun] = ("%s", entry->d_name); // Put the file name in the array.
        coun++;
            printf("%*s - %s\n", depth, "", entry->d_name); // This will print the file.
        }
    }

    chdir("..");
    closedir(dp);
}

int main(int argc, char* argv[])
{
    word = calloc(1000, sizeof(*word));
    printdir(".", 0);
    printf("now, print the words in the order they were printed.\n");

    for (int i = 0; i < coun; ++i)
    {
        printf("%s\n", word[i]);
    }

    exit(0);
}

我编写此代码的主要目的是为当前目录中的文件创建树结构。当我 运行 它时,我得到这个输出。

- hw2
  - tree
  - Makefile
  - ls.c
  - tree.c
  - find.c
- hw1
  - grep.c
  - factor.c
  - uniq.c
  - monster.c
  - sort.c
 - .nfs0000000006c543ea0000e073
 - tree.c
 - tree
now, print the words in the order they were printed.
hw2
grep.c






hw1
grep.c
factor.c
uniq.c
monster.c
sort.c
.nfs0000000006c543ea0000e073
tree.c
tree

树工作正常,但之后我仍然需要对文件进行排序。我的计划是将所有文件名放入全局单词数组中,然后区分文件夹和文件,并以相同的格式打印,但按字母顺序排列,不区分大小写。 我检查了阵列,但 hw2 文件夹及其文件被完全覆盖。我不明白为什么会这样,因为它应该工作正常。 有谁知道修复方法或更好的方法吗?

我认为您的问题出在这里:

word[coun] = ("%s", entry->d_name);
  • 您尚未分配任何内存 space 供 word[coun] 指向。
  • 我不知道 ("%s", ...) 的目的是什么,但是 gcc 对此发出了警告。它实际上 return entry->d_name"%s 未使用。
  • word[coun] 指向的内容在您尝试访问之前发生了变化。相反,您需要使用 strcpyentry->d_name 复制到您分配的内存 space 中。

而不是:

word[coun] = ("%s", entry->d_name); 
coun++;

你想要:

word[coun] = malloc(strlen(entry->d_name) + 1);
strcpy(word[coun++], entry->d_name);

确保为终止每个 C 字符串的 '[=20=]' 分配一个额外的字节。