c语言 - 找不到__fpurge(标准)的替代品;



我正在用 C 语言研究文本文件主题,我有一个问题:我可以使用什么来代替__fpurge(stdin);但要让这个函数像__fpurge(stdin);一样工作,我不允许在这个程序中包含<stdlib.h>。我已经读过这个 c - 需要一个 fflush 的替代品,但只要我不允许#include <stdlib.h>所以我不能使用strtol.

void generateBill() {
FILE *fp, *fp1;
struct Bill t;
int id, found = 0, ch1, brel = 0;
char billname[40];
fp = fopen(fbill, "rb");
printf("IDtNametPricenn");
while (1) {
fread(&t, sizeof(t), 1, fp);
if (feof(fp)) {
break;
}
printf("%dt", t.pid);
printf("%st", t.pname);
printf("%dtttn", t.pprice);
total = total + t.pprice;
}
printf("nn=================== Total Bill Amount %dnn", total);
fclose(fp);
if (total != 0) {
//__fpurge(stdin);
printf("nnn Do you want to generate Final Bill[1 yes/any number to no]:");
scanf("%d", &ch1);
if (ch1 == 1) {
brel = billFileNo();
sprintf(billname, "%s%d", " ", brel);
strcat(billname, "dat");
fp = fopen(fbill, "rb");
fp1 = fopen(billname, "wb");
while (1) {
fread(&t, sizeof(t), 1, fp);
if (feof(fp)) {
break;
}
fwrite(&t, sizeof(t), 1, fp1);
}
fclose(fp);
fclose(fp1);
fp = fopen(fbill, "wb");
fclose(fp);
}
total = 0;
}
}

用于替换__fpurge(stdin)建议:

int ch;
while( (ch = getchar() ) != EOF && ch != 'n' ){;}

只需要#include <stdio.h>

__fpurge是一个非标准函数,仅在某些系统(glibc 2.1.95,IBM zOS...)上可用,这些系统会丢弃读取到getc()尚未使用的流缓冲区中的输入。

正如 linux 手册页中所解释的,通常想要丢弃输入缓冲区是错误的。

使用scanf()读取用户输入,这会在请求的转换完成时停止扫描输入,例如,当用户读取无法继续数字的字符并将此字符保留在输入流中时,%d停止读取用户键入的字符。由于stdin在连接到终端时通常是行缓冲的,因此您应该在处理输入后读取并丢弃用户输入的线路中的任何剩余字节。

下面是一个用于此目的的简单函数:

int flush_input(FILE *fp) {
int c;
while ((c = getc(fp)) != EOF && c != 'n')
continue;
return c;
}

您将在处理用户输入后调用此函数,并且应测试scanf()的返回值以确保用户输入具有预期的语法。

以下是函数的修改版本:

#include <errno.h>
#include <string.h>
// return a non zero error code in case of failure
int generateBill(void) {
FILE *fp, *fp1;
struct Bill t;
int id, found = 0, ch1, brel = 0;
char billname[40];
fp = fopen(fbill, "rb");
if (fp == NULL) {
fprintf(sdterr, "cannot open %s: %sn", fbill, strerror(errno));
return 1;
}
printf("IDtNametPricenn");
while (fread(&t, sizeof(t), 1, fp) == 1) {
printf("%dt", t.pid);
printf("%st", t.pname);
printf("%dtttn", t.pprice);
total = total + t.pprice;
}
printf("nn=================== Total Bill Amount %dnn", total);
if (total != 0) {
int res;
printf("nnn Do you want to generate Final Bill[1 yes/any number to no]:");
while ((res = scanf("%d", &ch1)) == 0) {
fprintf("Invalid input. Try againn");
flush_input(stdin);
}
flush_input(stdin);
if (res == EOF) {
fprintf("premature end of file on inputn");
fclose(fp);
return 2; 
}
if (ch1 == 1) {
brel = billFileNo();
snprintf(billname, sizeof billname, "bill-%d-dat", brel);
rewind(fp);
fp1 = fopen(billname, "wb");
if (fp1 == NULL) {
fprintf(sdterr, "cannot open %s: %sn", billname, strerror(errno));
fclose(fp);
return 1;
}
while (fread(&t, sizeof(t), 1, fp) == 1) {
fwrite(&t, sizeof(t), 1, fp1);
}
fclose(fp1);
}
}
fclose(fp);
return 0;
}

最新更新