How to read a file to a linked list?

This is a discussion on How to read a file to a linked list? within the C Programming forums, part of the General Programming Boards category; I have a data file with following structure 111 (StudentID) Mary (StudentName) 30 (Score) 222 (StudentID) David (StudentName) 40 (Score) ...

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    5

    Question How to read a file to a linked list?

    I have a data file with following structure
    111 (StudentID)
    Mary (StudentName)
    30 (Score)
    222 (StudentID)
    David (StudentName)
    40 (Score)
    ........

    (20 records in this data file)


    I want to how to read these data into a linked list:

    Struct student {
    int studentID;
    char name[20];
    int score;
    struct student *next;
    };

    Thank you very much !!!

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >I want to how to read these data into a linked list:
    The same way you would read data from a file into any variable. Or are you asking how to read data from a file? Each data member in the record is on it's own line, this makes for insanely easy file input using functions such as fgets or fscanf, if you're implementing a linked list then you should know how to input data:
    fscanf ( fp, "%d\n%s\n%d", &s.id, s.name, &s.score );
    or
    s.id = atoi ( fgets ( buffer, sizeof buffer, fp ) );
    fgets ( s.name, sizeof s.name, fp );
    s.score = atoi ( fgets ( buffer, sizeof buffer, fp ) );

    Or some variation thereof. I didn't include any error checking, so you will need to include error checking and input validation. Especially with the scanf family of functions and the atoi fgets call, both of those can cause problems if you're not careful.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Linked List Help!
    By mbk in forum C Programming
    Replies: 3
    Last Post: 01-31-2008, 02:54 PM
  2. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 10:01 AM
  3. Problem with linked list ADT and incomplete structure
    By prawntoast in forum C Programming
    Replies: 1
    Last Post: 04-30-2005, 01:29 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 09:33 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM

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