I wrote this function as part of an HTML parser where I needed to read a line in and then do further parsing and editing of the text.
#include <stdio.h> #include <stdlib.h> /* The function get_next_line() */ char *get_next_line(FILE* fp) { int ch; int count = 0; int index = 0; if ((ch = fgetc(fp)) == EOF) return '�'; count++; while (ch != EOF) { if(ch == 'n') break; ch = fgetc(fp); count++; } char *buffer = (char *)malloc((sizeof(char)) * (count)); if (buffer == NULL) { printf("nmalloc error!"); exit(1); } fseek(fp, -(count), SEEK_CUR); for(index = 0; index < (count); index++) { ch = fgetc(fp); buffer[index] = ch; } buffer[index-1] = '�'; return buffer; } /* A sample implementation */ int main() { FILE *fp; char *line; int line_count = 0; if(!(fp = fopen("testing_main.c", "r"))) { printf("error opening file.n"); return 1; } while((line = get_next_line(fp)) != NULL) { printf("nLINE %d = %s",line_count, line); free(line); line_count++; } fclose(fp); return 0; }