Thread: Reading a file line by line

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #6
    Registered User
    Join Date
    Jul 2005
    Posts
    21
    Quote Originally Posted by cas
    feof() does not return EOF; or, at least, it is specificed as returning zero or non-zero, so it makes no sense to compare against EOF
    EOF is defined as -1 (in stdio.h), which is nonzero and aids in the reading of the code.

    Quote Originally Posted by cas
    string[strlen(string)] is always 0 (which is the same as '\0'), or undefined.
    That's true, apologies it was added in a rush. The use of feof is fine there, though removing it and following your example is more efficient. The loop looking like this now:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main( void ) {
    	short maxSize = 30;
    	char string[maxSize];
    	
    	FILE *fileptr = fopen("example.txt","r");
    	
    	while( fgets(string, maxSize, fileptr) != NULL ) {
    		printf("%s", string);
    		if( strlen(string) != maxSize - 1 ) {
    			printf(" Newline\n");
    		}
    		
    	}
    	
    	return 0;
    }
    Note that the size of the string array is set in a variable, the printf when the end of the string is detected isn't required, and blank lines, and the end-of-file also meet the conditions of the newline if statement.

    Apologies to Raskalnikov for the mess.
    Last edited by saeculum; 03-18-2009 at 07:43 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. reading words line by line from a file
    By -EquinoX- in forum C Programming
    Replies: 3
    Last Post: 05-04-2008, 12:34 AM
  3. Reading random line from a text file
    By helloamuro in forum C Programming
    Replies: 24
    Last Post: 05-03-2008, 10:57 PM
  4. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM