Thread: Reading from a file

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

    Reading from a file

    'lo everybody,

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

    Code:
    while( fscanf(input, "%c, %s, %s, %d, %c, %s, %c, %6s, %s, %s, %d, %d",
                     &i_r.rectype,
                     &i_r.cust_code,
                     &i_r.part_no,
                     &i_r.ir_quantity,
                     &del.rectype,
                     &del.cust_code,
                     &create.rectype,
                     &create.cust_code,
                     &create.cust_name,
                     &create.cust_address,
                     &create.cust_bal,
                     &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.

    Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > 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
    Code:
    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