Currently I'm doing my C programming homework. I'm facing a problem that I need to add some records to a text file using fprintf, then display out all the records within the file using fscanf. But here the display problem. It only skip the first character in the text, and display the rest. Example in the textfile,
hello haha 400 500 60
hello2 haha2 500 600 70
We need to fscanf this file into display in command prompt. But in result show me...
ello haha 400 500 60
hello2 haha2 500 600 70
The rest of characters is okay, but for the first character, it skipped. So this is my codes.
Fscanf's part
if ((ch = fgetc(fp)) != EOF){
while(fscanf(fp,"%s %s %d %d %d",code,name,&cost,&price,&stock) == 5)
{
printf("%-20s %-20s %-20d %-20d %-20d\n",code,name,cost,price,stock);
}
}else{
printf("Record not found in the stock database.\n");
puts("");
}
Fprintf's part
fprintf(fp,"%s %s %d %d %d\n",code,name,cost,price,stock);
So, how to read the first character ?
if ((ch = fgetc(fp))reads the first character. This is why it is skipped - Aserrefscanfis correct. Thefgetcis redundant. - Tom Fenechwhile(fscanf ...)) is ok. You should change yourif ((ch = fgetc(fp))though. Try something likeif (fp){ ... }orif(feof(fp)) {...}instead - Aserreungetcfunction. It allows returning (at least) 1 char to aFILE*stream. - hyde