Thread: Reading from a File

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    1

    Unhappy Reading from a File

    We are attempting to read a file, and input data into an array of structures. The array of structures is defined in the main program as:

    Code:
    fastfood ff[10];
    The structure is defined as:
    Code:
    typedef struct
    {
    char code[5];
    char food_name[13];
    int amount;
    }fastfood;
    Our function is called in the main program as:
    Code:
    for(i=0; i < 10; i++)
    ff[i] = read_info(fptr);
    where fptr is a pointer to the file.

    Here is our function:
    Code:
    fastfood read_info (FILE *fptr)
    {
    fastfood ff;
    char line[100];
    fgets(line, 100, fptr);
    ff.code[5] = char(strtok(line, " "));
    ff.food_name[13] = char(strtok(" ", " "));
    ff.amount = atoi(strtok(" ", "\n"));
    return ff;
    }
    Please find our many mistakes, or perhaps give us some helpful hints.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Boooo. Here's the easy fix:

    1) Use binary files.
    2) Use fread.
    3) Be amazed at how easy this was.

    fread( &ff, sizeof( fastfood ), 1, fptr );

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

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Code:
    fastfood read_info (FILE *fptr)
    {
    fastfood ff;
    char line[100];
    fgets(line, 100, fptr);
    ff.code[5] = char(strtok(line, " "));
    ff.food_name[13] = char(strtok(" ", " "));
    ff.amount = atoi(strtok(" ", "\n"));
    return ff;
    }
    Most of that looks rather nasty...
    - what is char? It's a reserved name for one, so it better not be a function.
    - check the return from strtok()
    - don't use strtok() if you not aware of its side affects (string alteration)
    - dont pass structures back from a function.

    All that said, Quzah is right, use better file io in the first place.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

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