代码之家  ›  专栏  ›  技术社区  ›  pistacchio

C:将文件读取到数组中

c
  •  1
  • pistacchio  · 技术社区  · 16 年前

    我有一个文本文件,我想一行一行地阅读它,并将这些行放入一个数组中。

    后面的代码段在编译时出错:

    FILE *f;
    char line[LINE_SIZE];
    char *lines;
    int num_righe;
    
    f = fopen("spese.dat", "r");
    
    if(f == NULL) {
        f = fopen("spese.dat", "w");
    }
    
    while(fgets(line, LINE_SIZE, f)) {      
        num_righe++;
        lines = realloc(lines, (sizeof(char)*LINE_SIZE)*num_righe);
        strcpy(lines[num_righe-1], line);
    }
    
    fclose(f);
    

    错误是:

    spese.c:29: warning: assignment makes integer from pointer without a cast
    spese.c:30: warning: incompatible implicit declaration of built-in function ‘strcpy’
    spese.c:30: warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast
    

    有什么帮助吗? 谢谢

    4 回复  |  直到 16 年前
        1
  •  5
  •   Emil H    16 年前

    尝试:

    FILE *f;
    char line[LINE_SIZE];
    char **lines = NULL;
    int num_righe = 0;
    
    f = fopen("spese.dat", "r");
    
    if(f == NULL) {
            f = fopen("spese.dat", "w");
    }
    
    while(fgets(line, LINE_SIZE, f)) {              
            num_righe++;
            lines = (char**)realloc(lines, sizeof(char*)*num_righe);
            lines[num_righe-1] = strdup(line);
    }
    
    fclose(f);
    
        2
  •  2
  •   Tom    16 年前

    我认为这是一个代码片段,因此,我猜你已经包括了string.h。

    strcpy定义为:

      char * strcpy ( char * destination, const char * source );
    

     strcpy(lines[num_righe-1], line);
    

    行[num_righe-1]是字符,而不是字符*

    所以应该是

    strcpy(lines + (num_righe-1), line);
    

    正如慷慨的作者所写,看起来你是在试图使行成为一个字符串数组。如果是这样,你对行的定义是错误的。

    另外,不要忘记,您应该检查realloc不返回空值。

    lines = realloc(lines, (sizeof(char)*LINE_SIZE)*num_righe);
    
    if (!lines) //MUST HANDLE NULL POINTER!!
    
    /* string copy code here*/
    
        3
  •  1
  •   munificent    16 年前

    lines 是指向字符的指针,即单个字符串。您希望它是一个字符串数组。为此,应该是 char **lines;

        4
  •  1
  •   foobarfuzzbizz    16 年前

    你可以用fscanf代替你想做的。

    fscanf(f, "%s\n", line[index]);
    index++;