Thread: Trying to read a .txt file into a linked list.

  1. #1
    Registered User
    Join Date
    Sep 2014
    Posts
    4

    Trying to read a .txt file into a linked list.

    Hey everyone! I'm new here, and new to the C language in general. I've been trying to read a .txt into a linked list in the attached code. I'm running into problems, specifically I'm getting errors on line 41 (curr->word=charTemp. I'm trying to set the word array equal to the charTemp array. I've tried strcpy with no luck . Any suggestions?

    Code:
    #include <stdio.h>#include <stdlib.h>
    #include <string.h>
    
    
    //Struct for linked list
    typedef struct node
    {
        char word[25];
        struct node *next;
    } node;
    
    
    
    
    //Start ##main##
    int main()
    {
        char c;
        char charTemp[25];
        int i = 0;
        
    //open files
        FILE *oneFile;
        oneFile=fopen("in1.txt", "r");
        
    //start linked list    
        struct node *root; //First node (unchanging)
        struct node *curr; //current node
        
        root = (struct node*) malloc(sizeof (struct node));
        root->next= 0;
        curr=root;
        
        
        do
        {
            c= fgetc(oneFile);
            
            if(fgetc(oneFile)==" ")
            {
                //enter data into linked list 
                curr->next = malloc( sizeof(struct node));
                curr->word=charTemp; ////#### PROBLEM CHILD
                curr = curr->next;
            }
            else
            {
                charTemp[i] =c;
            }
            
        }
        while(c != EOF);
        
    }//End ##main##
    Attached Files Attached Files

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > I've tried strcpy with no luck . Any suggestions?
    Use strcpy(), because it was the right thing to do.

    What you also need to do is make sure the string you're creating always has a \0 character at the end, otherwise it will copy garbage and/or crash.

    > if(fgetc(oneFile)==" ")
    Use
    if ( c == ' ' )
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    The first thing I notice is that your code appears poorly thought-out and planned (that is meant as an observation, not an insult). Starting with and maintaining an organized approach is quite helpful. You should develop a habit of working out a solution to your problem with paper and pencil, then turning that solution into pseudo code, then implementing that pseudo code in small chunks, compiling (at max warning level) and testing your code often.

    Compile with warnings set to maximum (-Wall option for GCC, else check your compiler docs):
    Code:
    $ make foo
    gcc -Wall -ggdb3 -pedantic -std=gnu99 -O0 -o foo foo.c -lm -lpthread -lrt
    foo.c: In function ‘main’:
    foo.c:40:26: warning: comparison between pointer and integer [enabled by default]
    foo.c:40:26: warning: comparison with string literal results in unspecified behavior [-Waddress]
    foo.c:44:23: error: incompatible types when assigning to type ‘char[25]’ from type ‘char *’
    make: *** [foo] Error 1
    On line 40, you're comparing the return value of fgetc (an int) with " ", a string literal, which is of type pointer to char. You can't compare int and pointer. Perhaps you meant to use single quotes, for a char literal: ' ' But that comparison is wrong anyway. You call fgetc twice, meaning only check every other char for a space, the char stored in c (from the first fgetc read) is never checked.

    On line 44, you can't assign arrays/strings. You must use strcpy to copy strings.

    You have several other problems as well:

    • Don't use magic numbers. #define a constant with a sensible name like MAX_WORD_LEN.
    • You should check the return value of fopen. If you fail to open the file, print a useful error (look into the perror() function) and return a failure from main with return EXIT_FAILURE;
    • You should check the return value of malloc. If it fails, print a useful error message (perror again). You probably want to return from main with a failure in this case too.
    • c should be declared an int because fgetc returns an int. It returns an int so it can return all possible char values as well as special values like EOF.
    • Your if/else inside the loop is broken. If c is EOF, you will copy it into charTemp. Change the else to else if (c != EOF).
    • Your code also doesn't properly handle multiple spaces in a row. Maybe this isn't a problem (the assignment states this will not occur in input files), or maybe it is.
    • Make sure to close your files and free all allocated memory when you're done.
    • It never hurts to be explicit, and return a value at the end of main. Put a return EXIT_SUCCESS; statement as the last line of main.


    The biggest problem though, which I mentioned above is planning/organization. This is extremely important as your programs grow in complexity. You should be using functions. Perhaps a function that extracts a single word from the file. Perhaps a function that adds a word to the end of the list. A print function that prints your list would be useful for testing. If you separate unrelated parts of code, it makes development, testing and debugging much simpler. Get the list working by just passing in words without reading from a file. Get reading from a file correct without worrying about inserting into a list. Then put the two together.

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. read/write linked list
    By lambs4 in forum C Programming
    Replies: 4
    Last Post: 03-29-2003, 06:38 PM
  3. read file into Linked list, please
    By unhwan in forum C Programming
    Replies: 3
    Last Post: 06-11-2002, 07:18 PM
  4. How to read a file to a linked list?
    By c beginner in forum C Programming
    Replies: 1
    Last Post: 04-09-2002, 10:59 AM
  5. Read Data-Linked list pro
    By Supra in forum C Programming
    Replies: 8
    Last Post: 09-15-2001, 05:34 PM

Tags for this Thread