Reputation: 1853
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?
Upvotes: 0
Views: 4025
Reputation:
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);
}
}
Upvotes: 2
Reputation: 40145
#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;
}
Upvotes: 0
Reputation: 43518
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++;
....
}
Upvotes: 0