Q2 Write a C program called myupper4c to take as command lin

Q2: Write a C program called myupper4.c to take as command line input a file name. It should then read the text file, one string at a time and store in a linked list each string. Each new string read from the file should be inserted at the END of the linked list. Each node of the linked list should contain 2 variables: i) a character array to hold a string, ii) a pointer to the next node in the linked list. The myupper4.c file should also contain a function void print_linked_list(struct *node) to iterate over the linked list and print the strings stored in each node of the linked list.

Solution

#include<stdio.h>
#include<stdlib.h>
#include<process.h>
#define MAX_LENGTH 512 // buffer size
typedef struct node
{
char data[MAX_LENGTH];
struct node *next;
} strNode;
  
int main ( int argc, char *argv[] )
{
   strNode *head;
strNode *current;
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
/* Assuming argv[0] it is the program name */
printf( \"Error in %s filename\", argv[0] );
       exit();
}
else
{
// argv[1] is a filename to open
FILE *file = fopen( argv[1], \"r\" );

/* fopen returns 0 on failure */
if ( file == 0 )
{
printf( \"Could not open file\ \" );
}
else
{
char str[MAX_LENGTH];
/* read one word at a time from file, stopping at EOF,
indicating the end of the file. */
while ( fgets(str,sizeof str,file)!=NULL )
{
               // check if list is empty
if (head == NULL)
               {
                   head = (strNode*) malloc(sizeof(strNode)); // create head node
                   strcpy(head->data, str);
               }
               // if list not empty
               else
               {
                   current = head; // start at the beginning
                   while (current->next != NULL)
                   {
                       current = current->next; // traverse to the end of the list
                   }
                   current->next = (strNode*) malloc(sizeof(strNode));
                   current = current->next;
                   strcpy(current->data, str);
                   display(current);
               }  
}
fclose( file );
}
}
   return 0;
}

void display(struct node *disp)
{
printf(\"%s \", disp->data);
if (disp->next == NULL)
{
return;
}
display(disp->next);
}

Q2: Write a C program called myupper4.c to take as command line input a file name. It should then read the text file, one string at a time and store in a linked
Q2: Write a C program called myupper4.c to take as command line input a file name. It should then read the text file, one string at a time and store in a linked

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site