Reputation: 408
I want to read lines of a text file, and the content of it is as below.
first
second
third
I've already written some code, but the result was different from what I expected. I hope you can help me a little. (code below)
/*
content of test.txt
first
second
third
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// double pointer for two string lines
// and the two string lines will be pointed by (char *) pointer
FILE *fp = fopen("test.txt", "r");
char **lst = malloc(3 * sizeof(char *)); // corrected 2 -> 3
// read lines until feof(fp) is not Null
// Only 2 lines will be read by this loop
int i = 0;
while (!feof(fp)) {
char line[10];
fgets(line, 10, fp);
*(lst + i) = line;
printf("%d : %s", i, *(lst + i));
i++;
}
/*
Result:
0 : first
1 : second
2 : third // Why was this line printed here?
There are 3 lines, not 2 lines!
*/
printf("\n\n");
int j;
for (j = 0; j < i; j++) {
printf("%d : %s\n", j, *(lst + j));
}
/*
result:
0 : third
1 : third
2 : third
The whole lines were not printed correctly!
*/
free(lst);
return 0;
}
Expected output:
0 : first
1 : second
2 : third
Many thanks.
Upvotes: 1
Views: 929
Reputation: 545528
First and foremost, you are allocating space for an array of two char*
s and you have a single statically sized buffer for a string. But you’re attempting to read three strings. Where do you think the space for the strings is coming from? You’re not allocating it.
You need to make your various numbers match up: allocate an array of three strings, and then allocate three string buffers:
char **lst = malloc(3 * sizeof *lst);
for (int i = 0; i < 3; i++) {
lst[i] = malloc(10);
fgets(lst[i], 10, fp);
}
And don’t forget to free
all allocated buffers subsequently:
for (int i = 0; i < 3; i++) {
free(lst[i]);
}
free(lst);
… of course this code isn’t terribly great either since it hard-codes the number of lines you can read, and the maximum line length. But it should get you started.
Upvotes: 1