Thread: Reading data from a file till there is a newline?

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    71

    Reading data from a file till there is a newline?

    this is what i am trying but it aint working

    Code:
    while (fptr == '\n')
             counter++;
    fptr is a file pointer and counter is counting the number of times there is a newline.

    why is it wrong? and what would be the right code otherwise


    can someone plz help
    thanks

  2. #2
    Unleashed
    Join Date
    Sep 2001
    Posts
    1,765
    The world is waiting. I must leave you now.

  3. #3
    Registered User
    Join Date
    May 2002
    Posts
    71
    thanks dude

    i think this does the job

    Code:
    void count (FILE *fptr, int *counter)
    {
    	char test[81];
    	while (fgets(test, sizeof (test), fptr))
    	{
    		(*counter)++;
    	}
    
    	printf("counter = %d\n", *counter);
    	
    	return;
    }
    for future reference for someone else

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    i think this does the job
    It does, but only for files that have lines <81 chars long. If you want to guarantee that you're counting all the newlines chars, you'd probably best check each character.

    Here's an extract from my manual for fgets():
    A common programming error is to assume the presence of a new-line character in every string that is read into the array. A new-line character will not be present when more than n-1 characters occur before the new-line. Also, a new-line character might not appear as the last character in a file, just before end-of-file.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  5. #5
    Registered User char's Avatar
    Join Date
    Apr 2002
    Posts
    31
    Code:
    char test [4096];  //seldom you will find lines larger than this size
    The best way though is to check every single character in the file.

    Code:
    int c, counter = 0;
    
    while ( (c = fgetc (fptr)) != EOF )
      if ( c == '\n' )
        counter++;
    
    if ( ferror (fptr) )
      printf ("Read Error\n"), exit (EXIT_FAILURE);

  6. #6
    Aniket002
    Guest

    Thumbs up Counting New Lines

    i'll prefer that last solution of counting lines ie
    c=fgetc(....)
    if (c=='\n')
    counter++

    this is the preferable and easy understandable soultion..

  7. #7
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    Another variation is to use the following, good for counting the number of variable size records, each terminated by a new line character, on a text file.

    Code:
    #define MAX_LEN /*whatever you think appropriate */
    
    char str[MAX_LEN];
    
    fscanf("%[^\n]\n", str);
    while(str != EOF) 
    {
              counter++;
              fscanf("%[^\n]\n", str);
    }
    the fscanf will read the data up to the new line character and the next "\n" takes reads the newline at the end of the record.
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

  8. #8
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Originally posted by bigtamscot
    Another variation is to use the following, good for counting the number of variable size records, each terminated by a new line character, on a text file.
    <-- snip code -->
    the fscanf will read the data up to the new line character and the next "\n" takes reads the newline at the end of the record.
    Did you compile that, 'cos I couldn't. fscanf() is defined as
    int fscanf( FILE *fp, const char *format, ... );
    You are missing some parms. Also, fscanf return EOF, it doesn't place it into one of its parameter variables.

    Even when I fixed these bits, it still didn't give the correct answer, so I'm not sure the "%[^\n]\n" bit is correct.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  9. #9
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Code:
    #define MAX_LEN /*whatever you think appropriate */
    
    char str[MAX_LEN];
    
    fscanf("%[^\n]\n", str);
    while(str != EOF) 
    {
              counter++;
              fscanf("%[^\n]\n", str);
    }
    str is a reserved name, fscanf doesn't have the correct arguments, str will never be EOF, and the whole %[^\n]\n format is just nasty. Even with the errors fixed this code wouldn't give the correct output, perhaps something more like this:
    Code:
    #define MAX_LEN /*whatever you think appropriate */
    
    char fstr[MAX_LEN];
    
    while ( fgets ( fstr, sizeof fstr, file ) != NULL ) 
      counter++;
    -Prelude
    My best code is written with the delete key.

  10. #10
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    1, no i never did compile it.
    2, sorry i forgot the file stream in the parameters.
    3, I have never had any problems with it, although i would never use it where i was not sure whether the len of string would go out of bounds.

    Sorry guys a quick thought when i was at work and posted in a hurry.
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

  11. #11
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    Okay folks compiled my code above and it crashed severely. It needed a few alterations. I donot know if it is more efficient than the other methods shown, but it does work, as long as the length of the maximum line on the file is no longer than MAXSIZE.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAXSIZE 150 /*OR ANY LEN YOU NEED*/
    
    int main (void)
    {
      char str[150];
      FILE  *infp;
      int count = 0;
    
      if((infp = fopen("myfile.dat", "rt"))== NULL) {
    		printf("\nE R R O R : Unable to open input file");
    		exit (1);
      }
      printf("\nNow counting number of records on file");
    
      while((*str = fgetc(infp))!= EOF) {
    			fscanf(infp,"%[^\n]\n", str);
    			count++;
    			}
      
      printf("\n\nNumber of records on file is %d", count);
      getchar();
      fclose(infp);
      return 0;
    }
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

  12. #12
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Have another read of Preludes comments on your code....
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  13. #13
    Registered User
    Join Date
    Jun 2002
    Posts
    18

    how would I?

    I have array of string which have
    one meaning of one
    two meaning of two
    three meaning of three

    For example, "one" is a word and "meaning of one" is a meaning of one. How would I divide each line into two pieces so I can have word and meaning separately?

  14. #14
    Registered User TravisS's Avatar
    Join Date
    Jun 2002
    Posts
    536
    I personally would use either strstr or strch

    I think you can use strch with \n, but I could be wrong, in which as strstr would be better.

    SO, I would do:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAXSIZE 150 /*OR ANY LEN YOU NEED*/
    
    int main (void)
    {
      char str[150];
      FILE  *infp;
      int count = 0;
    
      if((infp = fopen("myfile.dat", "rt"))== NULL) {
    		printf("\nE R R O R : Unable to open input file");
    		exit (1);
      }
      printf("\nNow counting number of records on file");
    
      while((*str = fgetc(infp))!= EOF) {
    			if( strch(str, '\n') )
    			  count++;
    			}
      
      printf("\n\nNumber of records on file is %d", count);
      getchar();
      fclose(infp);
      return 0;
    }
    Assuming I understand your code and your question, which I'm pretty sure I do.

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    while((*str = fgetc(infp))!= EOF) {
    if( strch(str, '\n') )
    count++;
    }
    Um... no. This is entirely wrong. What is this even supposed to do? First off, 'str' is an array, and you're dereferencing it ... and then you try to use .... yeah. Anyway it's wrong.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question regarding reading data from file into arrays
    By vutek0328 in forum C Programming
    Replies: 3
    Last Post: 05-29-2007, 09:20 AM
  2. reading in file data
    By sickofc in forum C Programming
    Replies: 2
    Last Post: 03-01-2006, 05:16 PM
  3. reading data into a queue from file
    By bcianfrocca in forum C++ Programming
    Replies: 12
    Last Post: 11-17-2005, 11:28 AM
  4. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  5. reading data from a file
    By brianptodd in forum C++ Programming
    Replies: 1
    Last Post: 11-07-2003, 06:50 PM