这是items.txt包含的内容:
275,Fresh Fish,12.34,0
386,Soft kleenex,45.67,1
240,Ultra Tide,24.34,1
916,Red Apples,123.45,0
385,Magic Broom,456.78,1
495,Liquid Soap,546.02,1
316,Chocolate Cookies,78.34,1
355,Organic Milk,24.34,0
846,Dark Chocolate,123.45,1
359,Organic Banana,99.99,0
当用户输入“Y”时,如何回放文件?如果我第一次输入正确的值,它就会起作用。
#include <stdio.h>
#define TAX (0.13)
void keybFlush(){
while(getchar() != '\n');
}
int getInt(){
int val;
char nl = 'x';
while (nl != '\n'){
scanf("%d%c", &val, &nl);
if (nl != '\n'){
keybFlush();
printf("Invalid Integer, please try again: ");
}
}
return val;
}
int yes(){
char ch = 'x';
int res;
do{
ch = getchar();
res = (ch == 'Y' || ch == 'y');
keybFlush();
} while (ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N' && printf("Only (Y)es or (N)o are acceptable: "));
return res;
}
int main(){
int upc, userUpc, found = 0;
double price;
int isTaxed, i;
char item[21], ch, x, y;
FILE* fptr = fopen("items.txt", "r");
if (fptr){
do {
userUpc=getInt();
printf(" UPC | Name | Price | Tax | Total\n"
" -----+--------------------+-----------+---------+-----------\n");
printf("its : %d\n", userUpc);
while (!feof(fptr)){
fscanf(fptr, "%d,%[^,],%lf,%d", &upc, item, &price, &isTaxed);
if ( upc == userUpc){
if(!feof(fptr)){
printf("%-6d|%-20s|%11.2lf|", upc, item, price);
if (isTaxed)
printf("%9.2lf|%11.2lf\n", price * TAX, price * (1+TAX));
else
printf("%9.2lf|%11.2lf\n", 0.0, price);
found = 1;
}
}
}
if (!found){
printf("Can't find any matched records\n");
}
printf("Do you want to continue: ");
i=yes(); // if yes, rewind the file
} while (!userUpc || (i == 1));
fclose(fptr);
}
else{
printf("could not open the file\n");
}
return 0;
}
如果我输入“y”继续和正确的值,它似乎无法正确输出。
答案 0 :(得分:0)
要将文件光标的位置更改为文件的开头:
fseek(filePtr, 0, SEEK_SET);
更多关于文件操作: http://www.gnu.org/software/libc/manual/html_node/File-Positioning.html