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", ¤t->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