Skip to content

Instantly share code, notes, and snippets.

@kahless62003
Last active January 9, 2016 21:52
Show Gist options
  • Save kahless62003/8958970224db16be4b23 to your computer and use it in GitHub Desktop.
Save kahless62003/8958970224db16be4b23 to your computer and use it in GitHub Desktop.
Basic file reading code with many comments
/*This program will read characters from a file, and for each line:
* print it, followed by the count of the characters in that line.*/
#include <stdio.h>
int main(void)
{
char filename[]="testinputfile.txt";
/*This is a pointer that will point to the file (a single point in the file, not a whole line).
It does not point to anything yet.*/
FILE *file_pointer;
char c; /*This will hold the character we read from the file.*/
int counter=0; /*This will hold the number which we will increment each time we read a character that is not \n or EOF.*/
file_pointer = fopen (filename, "r"); /* Now the file_pointer should point to something.*/
if (file_pointer == NULL) /*If the pointer does not point to the file, do NOT try to process anything, but exit safely.*/
{
fputs ("Failed to open file.\n", stderr);
return 1;
}
else /* The file_pointer now does point to the start of the file. */
{
/* The do-while, does not check the exit condition until the end of the iteration.
* Therefore the last character fget will get from the file will be the EOF,
* which we do not want to print either.*/
do
{
c = fgetc(file_pointer); /* Get a character from where the file_pointer is pointing. */
/* If this character is not the EOF, print the character.
* This will ensure the newlines from the file will be printed like before,
* but does not try to print the EOF. */
if (c != EOF)
{
printf("%c", c);
}
/* If this character is both neither a '\n' (new line) nor an EOF, increment the counter,
* as we do not want the newline to be counted in the counter variable.*/
if (c != '\n' && c != EOF)
{
counter++;
}
/* Otherwise if the character is a new line, print then zero the counter variable.*/
else if (c == '\n')
{
printf("%i\n", counter);
counter=0;
}
/* As the last line may not end in a newline, but instead an EOF we check for it and a non-zero counter.
* As there is no newline preceding the EOF in this test, we will need to print an extra one before the number, if there /is/ a number.
* If number is zero, the last valid line was already processed and we do not print anything now.*/
else if (c == EOF && counter!=0)
{
printf("\n%i\n", counter);
counter=0;
}
}
while (c != EOF);
}
fclose(file_pointer);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment