0

I am using dev C++. I am making this simple function calles void quan(). It involves file handling, reading and appending. The problem is after I input something, it crashes. I dont know why and I think it is because of the fscanf?

void quan()
{
    FILE *fp,*fp1;
    int q;
    char name[20];

    fp=fopen("inv.txt","r");
    fp1=fopen("temp.txt","a");

    if(fp==NULL)
    {
        printf("quan error");
    }
    else
    {

        printf("enter product name: ");
        gets(name);

        while(fscanf(fp,"%s %d %f %s",s.prod,s.quant,s.price,s.day)==4 )
        {
            if(strcmp(s.prod,name)!=0)
            {
                fprintf(fp1,"%s %d %.2f %s\n",s.prod,s.quant,s.price,s.day);

            }
            else
            {
                printf("enter quantity: ");
                scanf("%d",&q);
                s.quant=s.quant+q;
                fprintf(fp1,"%s %d %.2f %s\n",s.prod,s.quant,s.price,s.day);
                printf("\nsuccess");
            }
        }
    }

    fclose(fp);
    fclose(fp1);

    remove("inv.txt");
    rename("temp.txt","inv.txt");
}

this is inside my inv.txt file

apple 100 20.00 01/01/2015
orange 100 10.00 01/01/2015
banana 50 15.00 01/01/2015
grapes 15 10.00 01/01/2015
fan 100 5.00 01/01/2015
Eyam Saye
  • 39
  • 7

2 Answers2

0

You haven't declared what's s in fscanf, that's why the pointer won't work and your app crashes. Try using &s.prod, &s.prod, &s.quant, &s.price, &s.day

franpen
  • 322
  • 1
  • 4
  • 18
0

Since you are opening two files, you have to check both for error,

if( fp == NULL || fp1 == NULL )

you should use appropriate variable names in your code. Example: instead of fp you can use inputFile, this will give appropriate meaning and make the code more understandable to the reader.

fscanf scans input according to format conversion specifications from a file. The results from such conversions are stored in the locations pointed to by the pointer arguments that follow format. so you have to pass the address of the variable to store the matching conversions,

Example:

fscanf( fp, "%19s %d %f %10s", s.prod, &s.quant, &s.price, s.day)

(Assuming s.prod is an array of size 20 and s.day is also an array of size 11).

Specifying the size for the string in fscanf format will avoid overrunning the array.

Also, You don't need to specify & for array, because the array is already passed as an address, whereas the integer and float variable is not (and thus explicitly needs its address passed via the & address-of operator &).

Your compiler will throw warnings, if their is a argument mismatch for fscanf function. you should fix those warning before running the program to avoid runtime crashes.

Sridhar Nagarajan
  • 1,085
  • 6
  • 14