Member Avatar for loserspearl

I am trying to read a file and follow instructions based on its contents, add them to a linked list. I have the all the file handling written but am still having trouble with pointers and linked lists. The instructions from the input file would go like this

i n // insert value n into the list
c // clear thelist
q // quit

So if the content was:
i 1
i 2
i 3
i 4
q

The output would be:
1
1 2
1 2 3
1 2 3 4

Here is the file handling code for reference

#include <ctype.h>
#include <assert.h>

int main(int argc, char * argv[])
{
   assert(argc == 3);
   Node * p = NULL;
   int newval, retval;
   int op;

   FILE *in = fopen(argv[1],"r");
   assert(in != NULL);
   FILE *out = fopen(argv[2],"w");
   assert(out != NULL);
   do {
      op = fgetc(in);
   }  while (op != EOF && isspace(op));

   while(op != EOF && op != 'q') {
      switch(op) {
     case 'i':
        fscanf(in,"%d",&newval);
        p = orderedInsert(p,newval);
        printList(out,p);
        printList(stdout,p);
        break;
     case 'c':
        clearList(&p);
        break;
     default:
        fclose(in);
        fclose(out);
        return 0;
      }
      do
     op = fgetc(in);
      while (op != EOF && isspace(op));
   }

   fclose(in);
   fclose(out);
   return 0;
}

Here is my struct:

    typedef struct node {
       int data;
       struct node *next;
    } Node;

And these are my functions and what I'm trying to do with them, I'm just not exactly sure how.

  1. Allocates a new Node with data value newval and inserts into the ordered list with first node pointer p in such a way that the data values in the modified list are in an increasing order as the list is traversed.

    Node *orderedInsert(Node *p, int newval) {
    }

  2. Prints the data values in the list with first node pointer p from first to last, with a space between successive values. Prints a newline at the end of the list. I think I will be using fprintf(outfile, "%d\n", p-> data); but I'm not sure how to handle successive values.

    void printList(FILE *outfile, Node *p) {
    }

  3. Deletes all the nodes in the list with first node pointer *p, resulting in *p having value NULL. Note that we are passing a pointer by address so we can modify that pointer.

    void clearList(Node **p) {
    }

This tutorial may help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.