除了计算我移动了多少个空格之外。有没有一种简单的方法可以让缓冲区回到行的开头进行读取?我正在尝试读取字符串,然后返回读取不同的字符串和数字。它不按顺序,所以我必须回去专门寻找它们。我该怎么做。
我使用rewind(fp);
,但这会返回到文件的开头。
我还尝试在字符串后面读取整数。问题是很难读取两位数、三位数的数字。我能做到。但正如你所看到的,下面的函数一团糟。有没有更简单的方法来读取多位整数;
void get_total(FILE*fp, int* ptotal, int* pscores, int* pnum_quiz){
char c;
int i = 0;
int total=0;
int digits;
int first, second, third;
*pnum_quiz = 0;
int number_of_conversions;
number_of_conversions = fscanf(fp, "%c", &c);
while (isdigit(c) || isspace(c) && c !='\n' && c !=NULL && number_of_conversions!=0 && number_of_conversions !=EOF){
if (isspace(c)){
number_of_conversions = fscanf(fp, "%c", &c);
}
else if (isdigit(c)){
first = c - '0'; // convert a character integer to integer
*(pscores + i) = first;
i++;
number_of_conversions = fscanf(fp, "%c", &c);
digits = 1;
if (isdigit(c)){
second = c - '0';
*(pscores + i) = second;
i++;
number_of_conversions = fscanf(fp, "%c", &c);
digits = 2;
if (isdigit(c)){
third = c - '0';
*(pscores + i) = third;
i++;
digits = 3;
}
else{
fseek(fp, -1, SEEK_CUR);
*(pscores + i) = -1;
i++;
}
}
else{
fseek(fp, -1, SEEK_CUR);
*(pscores + i) = -1;
i++;
*(pscores + i) = -1;
i++;
}
if (digits==3){
total = total + (first * 100) + (second * 10) + third;
}
else if (digits==2){
total = total + (first * 10) + second;
}
else {
total = total + first;
}
number_of_conversions = fscanf(fp, "%c", &c);
}
number_of_conversions = fscanf(fp, "%c", &c);
*pnum_quiz = *pnum_quiz + 1;
}
*ptotal = total;
}
最佳答案
您可以向后fseek
浏览文件,但在我看来,这不是一个好的选择。
只需读取整行并将其存储在 char
缓冲区中。您的代码通过重复调用 fscanf(fp, "%c", &c)
来实现这一点,这是不必要的笨拙。已经有一个函数可以执行此操作,fgets
:
char line[80];
while (fgets(line, sizeof(line), fp) != NULL) {
// Now scan line instead of fp
}
现在您可以根据您的输入格式解析line
:如果您有固定格式,则sscanf(line, ..)
。如果需要提取 token 等,请重复strtok
。 (您没有显示输入的格式,但可能有一个函数可以比手动编码更好地处理它。)
fgets 的一个潜在问题是您需要指定最大长度,如果您可以有任意长的行,则这可能不合适。每行末尾留下的换行符也很烦人。
关于c - 如何在读取文件时倒回到行首。 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29998648/