简体   繁体   中英

Read file and save each line to variable in C

I'm using fgetc and fopen to read a file in C. I'd like to get the first line in a variable and a second line in a separate variable like so:

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
}

So if textfile has:

hello world
goodbye world

line1 = "hello world" line2 = "goodbye world"

I'm thinking of looping until a \\n but how should I store the characters? Think this is a simple question and maybe I'm missing something?

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);
    }
}
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++;
    ....
}
#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM