有条件地列出一个字符串数组

时间:2013-01-22 18:28:49

标签: c arrays string

我正在尝试列出C中给定目录中的所有文件和文件夹,以下代码出错,我无法弄清楚什么是错误的

#include <sys/types.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>

#include <unistd.h>
#include <pwd.h>

enum {
    WALK_OK = 0,
    WALK_BADPATTERN,
    WALK_BADOPEN,
};

int walk_directories(const char *dir, const char *pattern, char* strings[])
{
    struct dirent *entry;
    regex_t reg;
    DIR *d; 
    int i = 0;
    //char array[256][256];

    if (regcomp(&reg, pattern, REG_EXTENDED | REG_NOSUB))
    return WALK_BADPATTERN;
    if (!(d = opendir(dir)))
    return WALK_BADOPEN;
    while (entry = readdir(d))
    if (!regexec(&reg, entry->d_name, 0, NULL, 0) )
            //puts(entry->d_name);
        strings[i] = (entry->d_name);
        i++;
    closedir(d);
    regfree(&reg);

    return WALK_OK;
}

void main()
{
    struct passwd *pw = getpwuid(getuid());
    char *homedir = pw->pw_dir;
    strcat(homedir, "/.themes");

    int n = 0;
    char *array[256][100];
    char *array2[256][100];

    walk_directories(homedir, "", array);
        for (n = 0; n < 256; n++)
        {
            //do stuff here later, but just print it for now
            printf ("%s\n", array[n]);
        }

    walk_directories("/usr/share/themes", "", array2);
        for (n = 0; n < 256; n++)
        {
            //do stuff here later, but just print it for now
            printf ("%s\n", array2[n]);
        }
}

编译时的错误是

test2.c: In function ‘main’:
test2.c:42:2: warning: incompatible implicit declaration of built-in function ‘strcat’ [enabled by default]
test2.c:48:2: warning: passing argument 3 of ‘walk_directories’ from incompatible pointer type [enabled by default]
test2.c:15:5: note: expected ‘char **’ but argument is of type ‘char * (*)[100]’
test2.c:52:6: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Wformat]
test2.c:55:2: warning: passing argument 3 of ‘walk_directories’ from incompatible pointer type [enabled by default]
test2.c:15:5: note: expected ‘char **’ but argument is of type ‘char * (*)[100]’
test2.c:59:6: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Wformat]

如果有帮助,我已经在python中实现了我想要的东西,这是C的理想结果

import os
DATA_DIR = "/usr/share"

def walk_directories(dirs, filter_func):
    valid = []
    try:
    for thdir in dirs:
        if os.path.isdir(thdir):
            for t in os.listdir(thdir):
                if filter_func(os.path.join(thdir, t)):
                     valid.append(t)
    except:
    logging.critical("Error parsing directories", exc_info=True)
    return valid

def _get_valid_themes():
    """ Only shows themes that have variations for gtk+-3 and gtk+-2 """
    dirs = ( os.path.join(DATA_DIR, "themes"),
         os.path.join(os.path.expanduser("~"), ".themes"))
    valid = walk_directories(dirs, lambda d:
            os.path.exists(os.path.join(d, "gtk-2.0")) and \
            os.path.exists(os.path.join(d, "gtk-3.0")))
    return valid

print(_get_valid_themes())

谢谢

[编辑] 谢谢你的帮助,现在唯一的问题就是printf的所有吐出垃圾而不是我的预期,香港专业教育学院尝试了一些事情,而while循环现在看起来像这样

    while (entry = readdir(d))
    if (!regexec(&reg, entry->d_name, 0, NULL, 0) )
            //printf("%s\n",entry->d_name);
        strcpy(strings[i], (entry->d_name));
        //strings[i] = (entry->d_name);
        printf("%i\n",i);
        i++;
    closedir(d);

我也没有正确打印,这是我从3个printf语句得到的全部内容

0
Adwaita2





















\@




0
Radiance

��





\@



�K��
� `���
����
�


��
�
.N=

�O��
�

�

应该提一下,如果我启用

       printf("%s\n",entry->d_name);

然后它通过

打印预期的输出

2 个答案:

答案 0 :(得分:2)

  1. 您应该包含string.h以获取strcat(3)的声明。

  2. 在您的声明中:

    int walk_directories(const char *dir, const char *pattern, char* strings[])
    

    char *strings[]只是语法糖,意思是char **strings。由于您传递的是2D数组,因此无法正常工作。它看起来像你打算制作两个字符串数组,但这不是这些声明所做的:

    char *array[256][100];
    char *array2[256][100];
    

    您可能不希望*在那里。如果你取消它们,你可以将walk_directories的签名更改为:

    int walk_directories(const char *dir, const char *pattern, char strings[][100])
    

    它应该可以工作,在你的函数内部进行必要的更改以匹配。作为奖励,此更改也会使您的printf来电也开始工作。

  3. 看起来你错过了while循环体周围的一些大括号。

答案 1 :(得分:1)

第一个警告表明编译器无法确定strcat()函数应该采用的参数。由于这是标准的C函数,因此该警告意味着您缺少#include指令。具体来说,您需要#include <string.h>。当你解决这个问题时,你可能会发现你得到了不同的错误和警告,所以从那里开始工作。