C:将文件读入数组

pis*_*hio 1 c

我有一个文本文件,我想逐行读取它并将行放入一个数组.

后面的片段在编译时会出错:

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);
Run Code Online (Sandbox Code Playgroud)

错误是:

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
Run Code Online (Sandbox Code Playgroud)

有帮助吗?谢谢

Emi*_*l H 5

尝试:

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);
Run Code Online (Sandbox Code Playgroud)