Main.ReadingLinesFromAFileInC


How to read lines from a text file in C.

This example presumes no lines in the file are longer than 4Kb.

  FILE* myFile = fopen("file.txt", "r");
  if (!myFile)
  {
     printf("ERROR - could not open file.\n");
     exit(1);
  }
  char lineBuffer[4096];
  memset(lineBuffer, 0, 4096);
  fgets(lineBuffer, 4096, actionFile);
  while (!feof(actionFile))
  {
     printf("%s", lineBuffer);
     memset(lineBuffer, 0, 4096);
     fgets(lineBuffer, 4096, actionFile);
  }
  fclose(actionFile);

Spotting opportunities for more paranoid error checking is an exercise for the reader.