Thread: controlling contents of a linked list

  1. #1
    Registered User jaro's Avatar
    Join Date
    Mar 2006
    Location
    In my Parent House
    Posts
    34

    controlling contents of a linked list

    greeting!

    Just found a sample linked list program and I've decided to play around with it (hoping that I can incorporate it with the project I'm currently working on).

    here is the code: (this is only a quick hack/modification on the sample program that I've found, I haven't fix the warning message yet)
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct {
      char name[1000];
    } data;
    
    typedef struct {
      data  d;
      struct NODE *next;
    } NODE;
    
    #define CFG_FILE "Read.txt" // name of file to be open
    
    int main(void)
    {
      
    int num = 0;
    FILE *cfgfile;
    char data[80];
    int count = 1;		//display purposes
    
    NODE* head = NULL;  // this should always point to the 1st node
    NODE* pin = NULL;   // used to iterate through nodes. 
    
    
    	cfgfile = fopen ( CFG_FILE, "r" ); // open file, simulate the data retrieve from the database
    		if ( cfgfile == NULL )
    		{
    			perror ( "Error in reading text file containing cfg file location!!!" );
    		}
    		else
    		{
    			while ( fgets ( data, 80, cfgfile ) != NULL )  //delinmeter is newLine
    			{
    				printf("%d Line Read: %s",count++,data); // prints out the contents of Read.txt
    					if( head == NULL )
    					{
    						head = (NODE*) malloc(sizeof(NODE));
    						head->next = NULL;
    						pin = head;
    					}
    					else {
    						pin->next = (NODE*) malloc(sizeof(NODE));
    						pin = pin->next;
    						pin->next = NULL;
    					}
    				strcpy(pin->d.name,data);
    			}
    		fclose ( cfgfile );
    		}
    
    
    	//Printing the data. Goes through the linked list node by node.
    	printf("\n\n");
    	pin = head;
    	while( pin != NULL )
    	{
    		printf("%s", &pin->d.name);
    		num = num + strlen(pin->d.name);
    		pin = pin->next;
    	}
    	printf("\ntotal size of string is %d\n",num);
    
    	// cleanup
    	while( head != NULL )
    	{
    		pin = head->next;
    		free( head );
    		head = pin;
    	}
    
    	return 0;
    }
    the question is, what would I have to do in order for the contents of a linked list to be place in one string (character array).
    to elaborate more.
    let say the content of the Read.text (which can vary )are as follows:
    <DATA> 1
    <DATA> 2
    <DATA> 3
    <DATA> 4
    after reading the file and inserting the values to the linked list, how would I arranged the contents of the linked list into one string,
    into this format
    <DATA> 1<DATA> 2<DATA> 3<DATA> 4
    any kind of help or comment will be much appreciated.

    regards,
    jaro

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Code:
    {
      char *temp, *str = NULL;
      int len = 0;
      NODE *n;
    
      for(n = head;n;n = n->next)
      {
        if(!(temp = realloc(str, len + strlen(n->data) + 1)))
        {
          puts("Memory allocation error!");
          // do whatever you need to do here when you're out of memory
        }
        else
        {
          str = temp;
          strcpy(str + len, n->data);
          len += strlen(n->data);
        }
      }
    }
    Don't forget to free() str when you're done with it.
    Last edited by itsme86; 05-02-2006 at 10:21 AM.
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User 00Sven's Avatar
    Join Date
    Feb 2006
    Posts
    127
    Make another array and then just go to the beginnning of the linked list and put the string into the array with sprintf. Next loop through the list using strcat to add each string to the end.
    ~Sven
    Windows XP Home Edition - Dev-C++ 4.9.9.2
    Quote Originally Posted by "The C Programming Language" by Brian W. Kernignhan and Dennis M. Ritchie
    int fflush(FILE *stream)
    On an output stream, fflush causes any buffered but unwritten data to be written; On an input stream, the effect is undefined. It returns EOF for a write error, and zero otherwise. fflush(NULL) flushes all output streams.
    board.theprogrammingsite.com

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    sprintf(), or better yet, strcat().
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    Registered User jaro's Avatar
    Join Date
    Mar 2006
    Location
    In my Parent House
    Posts
    34
    Thanks for all of your responses.
    I now got an idea on how would approach this problem.

    Will post back soon for the complete code or if I found some weird error.

    -jaro

  6. #6
    Registered User jaro's Avatar
    Join Date
    Mar 2006
    Location
    In my Parent House
    Posts
    34

    final code,need ur comment

    just finished working on the program.
    Did some adjustment and add some extra function along the way.
    Just want to hear some comment about the code and if I violate some coding rules.

    here is the code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct {
      char name[1000];
    } data;
    
    typedef struct sNODE *nodePtr;
    
    typedef struct sNODE {
        data d;
        nodePtr next;
    } NODE;
    
    
    #define CFG_FILE "Read.txt" // name of file to be open
    //make global
    NODE* head = NULL;  // this should always point to the 1st node
    NODE* pin = NULL;   // used to iterate through nodes. 
    
    
    char* removeNewline(char line[])
    {
    	if (line[strlen(line)-1] == '\n')
    	{
    		line[strlen(line)-1] = '\0';
    	}
    	return line;
    }
    
    
    
    int stringLength(NODE* current) {
    	int count = 0;
    	current = head;
    		while (current != NULL) {
    			printf("%s", &current->d.name); // for display purpose only
    			count = count + strlen(current->d.name);
    			current = current->next;
    		}
    return count;
    }
    
    
    void linkCleanUp(NODE* last){
    	while( head != NULL )
    	{
    		last = head->next;
    		free( head );
    		head = last;
    	}
    }
    
    
    
    int main(void)
    {
      
    int strLen;
    FILE *cfgfile;
    char strdata[80];
    int count = 1;		//display purposes
    char *newstr;
    
    
    	cfgfile = fopen ( CFG_FILE, "r" ); // open file, simulate the data retrieve from the database
    		if ( cfgfile == NULL )
    		{
    			perror ( "Error in reading text file containing cfg file location!!!" );
    		}
    		else
    		{
    			while ( fgets ( strdata, 80, cfgfile ) != NULL )  //delinmeter is newLine
    			{
    				printf("%d Line Read: %s",count++,strdata); // prints out the contents of Read.txt
    					if( head == NULL )
    					{
    						head = (NODE*) malloc(sizeof(NODE));
    						head->next = NULL;
    						pin = head;
    					}
    					else {
    						pin->next = (NODE*) malloc(sizeof(NODE));
    						pin = pin->next;
    						pin->next = NULL;
    					}
    				strcpy(pin->d.name,strdata);
    			}
    		fclose ( cfgfile );
    		}
    
    
    	//Printing the data. Goes through the linked list node by node.
    	printf("\n\n");
    	strLen= stringLength(pin);
    	printf("\ntotal size of string is %d\n",strLen);
    
    	/* string them together.*/
    	newstr = malloc(strLen + 1);
    	newstr[0] = 0;
    	pin = head;
    		while (pin != NULL) {
    			strcat(newstr, pin->d.name);
    			removeNewline(newstr);
    			pin = pin->next;
    		}
    	printf("\n======= Entire string: =======\n%s\n", newstr);
    	free(newstr);
    
    	// cleanup
    	linkCleanUp(pin);
    
    	return 0;
    }
    The content of the Read.txt remains the same.
    output
    1 Line Read: <DATA> 1
    2 Line Read: <DATA> 2
    3 Line Read: <DATA> 3
    4 Line Read: <DATA> 4


    <DATA> 1
    <DATA> 2
    <DATA> 3
    <DATA> 4

    total size of string is 36

    ======= Entire string: =======
    <DATA> 1<DATA> 2<DATA> 3<DATA> 4
    Forgot to mention on my first post that I'm using MVC6 under Win2K.

    ~jaro

  7. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    removeNewline() doesn't have to return anything.

    Your while loop in stringLength() could be replaced with a for loop (but of course either will work).

    You read in a string into an 80-char buffer (data) and then copy it into d.data, a 1000-char buffer.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  8. #8
    Registered User jaro's Avatar
    Join Date
    Mar 2006
    Location
    In my Parent House
    Posts
    34
    thanks for your comment dwks.

    i'll try to make some changes regarding your suggestion.

    -jaro

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. linked list question
    By mikeman in forum C Programming
    Replies: 1
    Last Post: 11-30-2008, 01:56 PM
  2. Anyone good with linked list.....I am not....
    By chadsxe in forum C++ Programming
    Replies: 11
    Last Post: 11-10-2005, 02:48 PM
  3. Replies: 6
    Last Post: 03-02-2005, 02:45 AM
  4. linked list inside array of structs- Syntax question
    By rasmith1955 in forum C Programming
    Replies: 14
    Last Post: 02-28-2005, 05:16 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM