Thread: Reading from a file

  1. #1
    Registered User Inept Pig's Avatar
    Join Date
    Apr 2002

    Reading from a file

    'lo everybody,

    Is this the correct way to read data from a file?

    while( fscanf(input, "%c, %s, %s, %d, %c, %s, %c, %6s, %s, %s, %d, %d",
                     &create.credit_limit) !=EOF)
    I'm attempting to read all data from the file, and then to validate it. Any help offered is much appreciated.


  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > Is this the correct way to read data from a file?
    Whilst it might work if your data is well formatted, it does have some problems.

    You should really compare the result of fscanf with the number of conversions you expect, not EOF

    If fscanf returns say 5, then that leaves 7 values unassigned, and no way to tell that that is what happened. Even if you knew the result, it doesn't really help with error recovery.

    In addition, %c will almost certainly read the \n character from the previous line.

    Personally, I separate reading from the file and data validation
    char buff[BUFSIZ];
    while ( fgets( buff, BUFSIZ, input ) != NULL ) {
        // now validate buff and assign to fields
        // say using sscanf

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM