Thread: reading in a txt file into a list

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    67

    reading in a txt file into a list

    here is my code so far
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    typedef struct { char l[20]; struct List *next; } List;
    
    List *insertList (char head, List *tail)
    {
    	List *t = calloc (1, sizeof (List));
    	t -> l = head;
    	t -> next = tail;
    	return t;
    }
    
    
    static FILE *open_file (char *file, char *mode)
    {
      FILE *fp = fopen (file, mode);
      if (fp == NULL){
        perror ( "Unable to open file" );
        exit ( EXIT_FAILURE );
      }
      return fp;
    }
    
    int main (int argc, char *argv[])
    {
    int ch;
    FILE *in;
    
     if ( argc != 3 ) {
        fprintf ( stderr, "Usage: %s <readfile1> <writefile2>\n", argv[0] );
        exit ( EXIT_FAILURE );
      }
    
    	in = open_file ( argv[1], "r" );
    i am stuck on figuring out how to exactly read in a text file and put every separate word into a list, while ignoring commas.
    any ideas? cheers

  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
    Your insert head function would need to take a char array, and use strcpy to copy a word.

    Also, before you get complicated with reading a file, debug your list code with
    Code:
    int main ( ) {
      list = createList();
      list = insertList( "hello", list );
      list = insertList( "world", list );
      printList(list);
      deleteList(list);
      return 0;
    }
    When you've gotten the list functionality sorted, then look at using fgets() and strtok() to read lines, and split into words.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 02-02-2009, 07:27 AM
  2. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  3. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  4. compiler build error
    By KristTlove in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2003, 10:16 AM