Хранение и распечатка содержимого указателя связанного списка из двоичного файла - PullRequest
1 голос
/ 10 марта 2019

Пользователь должен ввести команды, которые затем добавят целые числа в связанный список, затем сохранят их в файл и, наконец, распечатают содержимое этого файла. Хотя я заставил его работать по существу, у меня возникла проблема, когда он не работал во время работы программы, поэтому, хотя он и добавляет в файл, он не делает этого во время выполнения. поэтому я могу использовать команду s, а затем команду l, чтобы увидеть новое содержимое, которое я только что сохранил в файл. Как я могу сделать это? Кроме того, как я могу определить, есть ли уже содержимое в файле, и если это так, сначала напечатайте ,.

ранец-shell.c

#include <stdio.h>
#include "knapsack.c"
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define BUFFER_SIZE 1000
void removeSpaces(char *str1)
{
    char *str2;
    str2=str1;
    while (*str2==' ') str2++;
    if (str2!=str1) memmove(str1,str2,strlen(str2)+1);
}

int main()
{
    listitemptr k2 = NULL;
    char input[100];
    char command;
    int i, returnval = 0;
    char filename[250];
    char userfile[260];
    char buffer[BUFFER_SIZE];
    char *error;
    int totalRead = 0;
   for (;;) {
       FILE* pf = NULL;
        fprintf(stdout, "> ");
        if (!fgets(input, sizeof input, stdin))
            break;
        i = strspn(input, " \t\n");  /* skip blanks */
        command = input[i++];

        if (command == 'q' && input[i] == '\n')
            break;
        if (command == 'p') {
            KnapsackPrint(&k2);
            continue;
        }
        if (command == 'a') {
            int item;
            if (sscanf(input + i, "%i", &item) != 1) {
                error = input + i;
                removeSpaces(error);
                fprintf(stderr, "Error: Bad item \"%s\"\n", strtok(input + i, "\n"));

                continue;
            }
            KnapsackAdd(&k2, item);
            KnapsackPrint(&k2);
            continue;
        }
        if (command == 'r') {

            int item;
            if (sscanf(input + i, "%i", &item) != 1) {
                error = input + i;
                removeSpaces(error);
                fprintf(stderr, "Error: Bad item \"%s\"\n", strtok(input + i, "\n"));
                continue;
            }

            if(KnapsackRemove(&k2, item) == -1){
                fprintf(stderr, "Error: item %d does not exist in knapsack\n", item);
                continue;
            }else{
            KnapsackPrint(&k2);
            continue;
            }

        }
        if(command == 's'){
            if(( pf = fopen(input + i, "a")) != NULL){
                error = input + i;
                removeSpaces(error);
                KnapsackPrint2(&k2, pf);
                fprintf(stdout, "stored in file \"%s\"\n", strtok(input+i, "\n"));
            }
            continue;
        }
        if(command == 'l'){
            if((pf = fopen(input + i, "r")) != NULL){
                error = input + i;
                removeSpaces(error);
                fprintf(stdout, "loaded from file \"%s\"\n", strtok(input+i, "\n"));

                while(fgets(buffer, BUFFER_SIZE, pf) != NULL){
                    totalRead = strlen(buffer);

                    buffer[totalRead -1] = buffer[totalRead -1] == '\n' ? '\0' : buffer[totalRead -1];

                    printf("%s\n", buffer);
                }

            }
            continue;
        }
        else{
        fprintf(stderr, "unknown command: %s", input);
        fprintf(stdout, "> ");
        }

    }
    return returnval;
}

knapsack.c

#include "knapsack.h"
#include <stdio.h>
#include <stdlib.h>

listitemptr KnapsackAdd(listitemptr *knapsack, int item){
   if(*knapsack==NULL){//empty list
       listitemptr newest= malloc(sizeof(struct listitem));
       newest->item=item;
       newest->count=1;
       newest->next=NULL;
       *knapsack = newest;
       return newest;
   }else{
       listitemptr current=*knapsack;
       listitemptr prev=NULL;
       while(current!=NULL){
           if(current->item == item){
               current->count=current->count+1;
               break;
           }else if(current -> item > item){
               listitemptr new_node = malloc(sizeof(struct listitem));
               new_node-> item = item;
               new_node-> count= 1;
               new_node-> next = current;
               if(prev != NULL ){
                   prev->next = new_node;
               }else {
                   *knapsack = new_node;

               }
               break;

           }
           prev=current;
           current=current->next;
       }
       if(current==NULL){
           listitemptr newest= malloc(sizeof(struct listitem));
           newest->item=item;
           newest->count=1;
           newest->next=NULL;
           prev->next=newest;
           return newest;
       }
       return current;
   }
}

int KnapsackRemove(listitemptr *knapsack, int item){
   if(*knapsack==NULL)
       return -1;
   listitemptr present=*knapsack;
   listitemptr previous=NULL;

   while(present!=NULL){
       if(present->item==item){
           if(present->count>1){
               present->count=present->count-1;
           }else{
               if(previous==NULL){ //delete at head
                   *knapsack=present->next;
               }else{
                   previous->next=present->next;
                   free(present);
               }
           }
           break;
       }
       previous=present;
       present=present->next;
   }

   return 0;
}

void KnapsackPrint(const listitemptr *knapsack){
   if(*knapsack==NULL)
       printf("knapsack: \n");
   else{
       listitemptr temp=*knapsack;
       printf("knapsack:");
       while(temp!=NULL){
           if((temp->next) == NULL){
               printf(" %d (%d)", temp->item, temp->count);
               break;
           }else{
           printf(" %d (%d),",temp->item,temp->count);
           temp=temp->next;
         }

       }
       printf("\n");
   }
}

unsigned int KnapsackItemCount(const listitemptr *knapsack, int item){
   if(*knapsack==NULL)
       return 0;
   listitemptr temp=*knapsack;
   while(temp!=NULL){
       if(temp->item==item)
           return temp->count;
       temp=temp->next;
   }
   return 0;  
}

unsigned int KnapsackSize(const listitemptr *knapsack){

   if(*knapsack==NULL){

       return 0;
   }

   listitemptr temp=*knapsack;
   unsigned int sum=0;
   while(temp!=NULL){
       sum+=temp->count;
       temp=temp->next;
    }
   return sum;


}

listitemptr KnapsackPrint2(const listitemptr *knapsack, FILE* fp){
   if(*knapsack==NULL)
       printf("knapsack: \n");
   else{
       listitemptr temp=*knapsack;
       fprintf(fp, "knapsack:");
       while(temp!=NULL){
           if((temp->next) == NULL){
               fprintf(fp, " %d (%d)", temp->item, temp->count);
               break;
           }else{
           fprintf(fp, " %d (%d),",temp->item,temp->count);
           temp=temp->next;
         }

       }
       printf("\n");
       return temp;
   }
}
...