Finding values in input file

This is a discussion on Finding values in input file within the C Programming forums, part of the General Programming Boards category; what is the best way to determine how many values are contained in an input pointer file and store in ...

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    11

    Question Finding values in input file

    what is the best way to determine how many values are contained in an input pointer file and store in a variable? any ideas appreciated.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Open the file.
    Read its contents.
    Store the restults.
    Close the file.

    Other than that, you'll have to clarify what you mean by "an input pointer file" and "store in a variable".

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

  3. #3
    Registered User
    Join Date
    May 2004
    Posts
    11
    sorry, i was a little vague, but actually im just looking for a function to read the # of data values in the file.

    like if file contained: 10,20,30,40,50,60
    the function would read 6 values... and store 6 in a variable
    i can use fscanf to read data but not to tell how many values are present.

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Some variant of this, perhaps?
    Code:
    /* file.txt
    10,20,30,40,50,60
    */
    
    #include <stdio.h>
    
    int main(void)
    {
       const char filename[] = "file.txt";
       FILE *file = fopen(filename, "r");
       if ( file )
       {
          int value, count = 0;
          while ( fscanf(file, "%d%*c", &value) == 1 )
          {
             ++count;
          }
          printf("count = %d\n", count);
          fclose(file);
       }
       return 0;
    }
    
    /* my output
    count = 6
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 01:44 PM
  2. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-22-2008, 12:19 AM
  3. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 02:04 PM
  4. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21