Thread: text files and linked list

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    1

    text files and linked list

    i need some help with writing all the words in a text file (separate by space) into a linked list then print the content of the linked list!!

    here is my code for word separated by a line break!! but i want help with the words separated by spaces...
    Code:
    FILE* f;
    f = fopen("test.txt", "r");
    char word[20];
    int count = 0;
    if (f == null)
    {
         perror("ERROR: \n");
    }
    
    else
    {
        while (feof(f) == 0)
        {
             fgets(word,20,f);
             count++;
             printf("%s", word);
        }
    }
    
    fclose(f);
    why does it also print out the last word twice?? :/

    your help will be appreciated!!

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by c_programmer14 View Post
    why does it also print out the last word twice??
    Because you are using feof incorrectly to control the loop. You can use feof to control the loop, but only if you use it correctly. You should just be using fgets to control the loop. (Cprogramming.com FAQ > Why it's bad to use feof() to control a loop)


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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read text file into a linked list
    By riddinon24z in forum C Programming
    Replies: 38
    Last Post: 08-04-2011, 01:49 PM
  2. Reading Text file in Linked list!
    By satty in forum C Programming
    Replies: 20
    Last Post: 07-29-2010, 08:48 AM
  3. Transferring text from file into linked list
    By manutdfan in forum C Programming
    Replies: 41
    Last Post: 01-22-2007, 06:19 AM
  4. print a text-file in linked list
    By tidemann in forum C Programming
    Replies: 10
    Last Post: 09-19-2006, 05:22 AM
  5. linked list and files...
    By 8ball in forum C Programming
    Replies: 3
    Last Post: 05-13-2004, 03:23 AM