PDA

View Full Version : data is showing up twice in the output


vishalkhialani
03-26-2007, 04:41 PM
Hello,
Please see my below code. Once you run it the data shows up twice from the file. Please advice why does this happen ?


/* fscanf example */
#include <stdio.h>


//creating a structure
struct attribute
{
int style;
char buyer[44];


}att;

int status=1;



int main ()
{

int stylenew;
char buyernew[44];

FILE * pFile;

printf("Please enter style number\n");
scanf("%d",&att.style);
printf("Please enter buyername\n");
scanf("%s",att.buyer);
pFile = fopen ("myfile.txt","a+");


fprintf (pFile, " %d %s", att.style,att.buyer);
rewind (pFile);

while(status!=EOF)
{
status=fscanf(pFile, "%d", &stylenew);
printf("--------------\n");
printf("%d",stylenew);
printf("+++++++++++++++++\n");
status=fscanf (pFile, "%s", buyernew);
printf("@@@@@@@@@@@@@@@@@@@@@@\n");
printf("%s",buyernew);
printf("$$$$$$$$$$$$$$$$$$$$$$$\n");

}
fclose(pFile);
return 0;

}

nikkiH
03-26-2007, 06:48 PM
You meant to append to the file, not overwrite?

vishalkhialani
03-27-2007, 12:40 AM
yes, I would like to apend the file.

Regards,
Vishal

nikkiH
03-27-2007, 02:33 PM
First thing I notice is the lack of checking for EOF on EVERY fscanf...
Other than that, let me compile and run it and see if I see odd repeating.

nikkiH
03-27-2007, 02:42 PM
Okay, this seems to work fine, assuming no spaces in the buyer name.


#include <stdio.h>

//creating a structure
struct attribute
{
int style;
char buyer[44];
} att;

int status=1;

int main ()
{
int stylenew;
char buyernew[44];

FILE * pFile;

printf("Please enter style number\n");
scanf("%d",&att.style);
printf("Please enter buyername\n");
scanf("%s",att.buyer);
pFile = fopen ("myfile.txt","a+");

fprintf (pFile, " %d %s", att.style, att.buyer);
rewind (pFile);

while(fscanf(pFile, "%d %s", &stylenew, buyernew) != EOF)
{
printf("--------------\n");
printf("%d",stylenew);
printf("+++++++++++++++++\n");
printf("@@@@@@@@@@@@@@@@@@@@@@\n");
printf("%s",buyernew);
printf("$$$$$$$$$$$$$$$$$$$$$$$\n");
}
fclose(pFile);

system("pause");
return 0;

}