Search code examples
cfiledocumentfgetc

Reading information from a file in C language


So I have the txt file from which I need to read the number of students written in that file, and because every student is in separate line, it means that I need to read the number of lines in that document. So I need to:

  1. Print all lines from that document

  2. Write the number of lines from that document.

So, I write this:

#include "stdafx.h"
#include <stdio.h>

int _tmain(int argc, _TCHAR* Argo[]){

    FILE *student;
    char brst[255];

    student = fopen("student.txt", "r");

    while(what kind of condition to put here?)
    {
        fgetc(brst, 255, (FILE*)student);
        printf("%s\n", brst);
    }

    return 0;
}

Ok, I understand that I can use the same loop for printing and calculating the number of lines, but I can't find any working rule to end the loop. Every rule I tried caused an endless loop. I tried brst != EOF, brst != \0. So, it works fine and print all elements of the document fine, and then it start printing the last line of document without end. So any suggestions? I need to do this homework in C language, and I am using VS 2012 C++ compiler.


Solution

  • Try this:

    #include "stdafx.h"
    #include <stdio.h>
    int _tmain(int argc, _TCHAR* Argo[]){
    FILE *student;
    char brst[255];
    char* result = NULL;
    
      //Ensure file open works, if it doesn't quit
    if ((student = fopen("student.txt", "r")) == NULL)
    {
      printf("Failed to load file\n");
      return 1;
    }
    
      //Read in the file
    for ( (result = fgets( brst, sizeof(brst), student)); 
          !feof(student); 
          (result = fgets( brst, sizeof(brst), student)) )
    {
      if ( result == NULL ) break; //I've worked on embedded systems where this actually ment waiting on data, not EOF, so a 'continue' would go here instead of break in that case
      printf("%s\n", brst);
    }
    fclose( student );
    return 0;
    }
    

    feof() is only true after you've read past the end of the file. Using a for with two identical reads, and feof() on the conditional is a simple way to ensure you read the file as expected.