C:函数未更新全局数组(使用strcpy / malloc)

哈坎

尝试从Windows中的目录获取文件名。通过名为list_files的函数来执行此操作。该函数由于某种原因(或其外观)未执行任何操作,导致每当我打印数组时,该函数为空。

我之前已经测试过此代码,并且运行良好。我一直在编码(原本是更长的代码),我注意到以后每次不得不使用数组时,它都会返回0(无)。

void list_files();

char *filesList[0][254];
int i = 0, n = 0, l = 254;
char directory[] = {"C:/Users/test/Downloads/test/"};

int main()
{
    list_files();
}

void list_files()
{
    DIR *d;
    struct dirent *dir;
    d = opendir(directory);
    //Determine the number of files
    while((dir = readdir(d)) != NULL) {
        if (strcmp(dir->d_name, ".") != 0 && strcmp(dir->d_name, "..") != 0)
            n++; // determine, count array size based on files
    }
    rewinddir(d);
    //Put file names into the array
    while((dir = readdir(d)) != NULL) {
        if (strcmp(dir->d_name, ".") != 0 && strcmp(dir->d_name, "..") != 0)
        {
            filesList[i][l] = (char*) malloc(sizeof(char) * 100); // allocate memory
            strcpy(filesList[i][l], dir->d_name); // put file names in to array
            i++; // do +1 to read each single array line
        }
    }
    rewinddir(d);
    printf("%s",n);
    for(i;i<n;i++){
        printf("%s/n", filesList[i][l]);
    }
}

我希望看到(或得到)的是一个目录中填充有文件名的数组。就我而言,该目录包含3个文件。该程序不适用于具有x00文件的大文件。所以当我打印数组时:

Hello.txt,bye.txt,bye.exe

用户名

使用char *fileList[254]申报254分的指针数组。
使用循环for(n = 0; n < i;n++){

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

void list_files();

char *filesList[254];
int i = 0, n = 0, l = 254;
char directory[] = {"./"};

int main()
{
    list_files();
}

void list_files()
{
    DIR *d;
    struct dirent *dir;
    d = opendir(directory);
    //Put file names into the array
    while((dir = readdir(d)) != NULL) {
        if ( ( i < 254) && ! ( strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0))
        {
            filesList[i] = malloc( strlen ( dir->d_name) + 1); // allocate memory
            strcpy(filesList[i], dir->d_name); // put file names in to array
            i++; // do +1 to read each single array line
        }
    }
    for(n = 0; n < i;n++){
        printf("%s\n", filesList[n]);
    }
    for(n = 0; n < i;n++){
        free ( filesList[n]);
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章