I am trying to read a line from file.txt and return it as string til maxchar
without using getline()
.
For example, if file.txt contains
c language
language c
Then:
printf("%s\n", get_line(f, 3))
printf("%s\n", get_line(f, 3))
should output
c l
lan
But my code returns weird characters.
#include <stdio.h>
#include <stdlib.h>
char *get_line(FILE *f, int maxchar) {
char *string = (char *)malloc(sizeof(f));
int c;
int i;
while ((c = fgetc(f)) != EOF && c != '\n') {
fgets(string, maxchar, f);
}
return string;
}
int main(void) {
FILE *f;
f = fopen("file.txt", "r");
printf("%s\n %s\n", get_line(f,3), get_line(f,5));
fclose(f);
return 0;
}
Is there any wrong in reading file? or using fgetc()
?
Any help would be appreciated.