0

我正在使用 fgetc 和 fopen 在 C 中读取文件。我想在变量中获取第一行,在单独的变量中获取第二行,如下所示:

f = fopen("textfile", "r");

if (!f) {
   printf("error");
} else {
   loop until end of newline and save entire line to a variable
   1st line ==> line1
   2nd line ==> line2
}

所以如果文本文件有:

hello world
goodbye world

line1 = “你好世界” line2 = “再见世界”

我正在考虑循环直到 \n 但我应该如何存储字符?认为这是一个简单的问题,也许我错过了什么?

4

3 回答 3

2

You want to:

I. use fgets() to get an entire line, then

II. store the lines into an array of array of char.

char buf[0x1000];
size_t alloc_size = 4;
size_t n = 0;
char **lines = malloc(sizeof(*lines) * alloc_size);
// TODO: check for NULL

while (fgets(buf, sizeof(buf), f) != NULL) {
    if (++n > alloc_size) {
        alloc_size *= 2;
        char **tmp = realloc(lines, sizeof(*lines) * alloc_size);
        if (tmp != NULL) {
            lines = tmp;
        } else {
            free(lines);
            break; // error
        }

        lines[n - 1] = strdup(buf);
    }
}
于 2013-04-18T19:22:29.240 回答
0
char line[NBRCOLUMN][LINEMAXSIZE];
int i =0; int len;
while (i<NBRCOLUMN && fgets(line[i],sizeof(line[0]),f)) {
    len = strlen(line[î]);
    if(line[len-1] == '\n') line[len-1] = '\0'; // allow to remove the \n  at the end of the line
    i++;
    ....
}
于 2013-04-18T19:21:34.707 回答
0
#include <stdio.h>

int main(int argc, char *argv[]){
    char line1[128];
    char line2[128];
    FILE *f;

    f = fopen("textfile", "r");
    if (!f) {
       printf("error");
    } else {
        fscanf(f, "%127[^\n]\n%127[^\n] ", line1, line2);
        printf("1:%s\n", line1);
        printf("2:%s\n", line2);
        fclose(f);
    }

    return 0;
}
于 2013-04-18T21:53:14.657 回答