I want to know
I want to know

Reputation: 49

C program failing to insert to file contents the previously read contents

I have this problem in my c program when I start to reinsert the contents of my file and save a new one. It fails in the while loop and i don't understand why it does that if i have some contents to reinsert from it.

here's my code: '''

void init(){
    char pn[30],pd[30],pp[30];
    if ((flptr = fopen("MASTER.dat","r+")) == NULL) { 
        printf("Couldnt Get Cred");
        return;
    }
    fscanf(flptr,"%s %s %s",pn,pd,pp);


    while(!feof(flptr)){
        r = (struct Records *) malloc(sizeof(struct Records));
        int fr = fscanf(flptr,"%s %s %f",r->PartNum,r->PartDesc, &r->PartPrice);
        if(fr == EOF){
            printf("HERE");
            break;
        }

        if(head == NULL){
           head = r;
         }
         else{
             tail->next = r;
         }
         tail = r;
         }

         fclose(flptr);
    }


void put(){
    if ((flptr = fopen("MASTER.dat","r")) == NULL) { 
        printf("Couldnt Get Cred");
        return;
    }

    r = head;
    fprintf(flptr,"PartNumber PartDescription PartPrice\n");

    while (r != NULL){
        fprintf(flptr,"%s %s %f\n", r->PartNum, r->PartDesc, r->PartPrice);
        r = r->next;
    }

    fprintf(flptr,"Changes SAVED.");
    fclose(flptr);
}

Upvotes: 0

Views: 41

Answers (1)

bruno
bruno

Reputation: 32596

In the function put you open the file to read it, not to write, so your fprintf will have no effect and the file not be even created

if ((flptr = fopen("MASTER.dat","r")) == NULL) { 

must be

if ((flptr = fopen("MASTER.dat","w")) == NULL) { 

If later you try to read that non existing file with init you will not success

Out of that put and init use the global variable r and modify it, I encourage you to use a local variable to avoid possible problems


Why do you open file file with "r+" in init while you only read it ?


When you read string through (f)scanf I encourage you to limit the length to not write out of the receiver with an undefined behavior, and to always check the result, so for instance replace

fscanf(flptr,"%s %s %s",pn,pd,pp);

by

if (fscanf(flptr,"%29s %29s %29s",pn,pd,pp) != 3) {
  printf("invalid file contain\n");
  return;
}

Upvotes: 1

Related Questions