我正在使用代码
while(fscanf(input, "%49[^@ ]@%49s -> %49[^@ ]@%49s", sender, trash, receiver, trash) != EOF){
printf("%s " "%s\n", sender, reciever);
}
尝试读取和打印文件中的每一行,但是当我运行此代码时,它会陷入无限循环,一遍又一遍地打印文件的第一行。执行此代码后,如何将扫描仪向下移动到下一行。预先感谢您的任何帮助。
#include < stdio.h >
FILE *fr;
main()
{
int n;
char line[80];
fr = fopen ("test.txt", "r"); /* open the file for reading */
while(fgets(line, 80, fr) != NULL)
{
/* get a line, up to 80 chars from fr. done if NULL */
sscanf ( line );
}
fclose(fr); /* close the file prior to exiting the routine */
}
做你想做的事的基本方法......
Do not compare against EOF, compare against the expected number of parsed fields.
while(3 == fscanf(input, " %49[^@ ]@%*49s -> %49[^@ ]@%49s", sender, receiver, trash)){
printf("%s " "%s\n", sender, receiver);
}
Some minor changes
Suspect you may want to skip over any leading whitespace, so begin format with " "
. ( I am sure this is contributing to your end-less loop. First scanning leave the \n
in the input queue. 2nd scan won't put \n
into sender
and fscanf()
returns 0, which is not EOF. Vicious cycle repeats.)
No need to save your first scanning of trash field with `"%49s". Use "*" to scan and not save.
Scan the second trash field and save to add to the scan count. This helps validate the incoming data is formatted as expected. An alternate pedantic check could be " %49[^@ ]@%*49s -> %49[^@ ]@%*49s%[\n]
.
BTW, recommend using fgets()
to get the line and use sscanf()
to tear apart. Easier to handle I/O and parsing errors.
fscanf()
返回进行的转换次数。EOF
仅在第一次转换失败时返回。正确的方法是:
while (fscanf(fp, "...", &v1, &v2, ...) == <number_of_variables_read>) {
...
}
if (ferror(fp)) ...
do {
fscanf(input, "%49[^@ ]@%49s -> %49[^@ ]@%49s", sender, trash, receiver, trash);
printf("%s " "%s\n", sender, reciever);
} while(!feof(input));
您应该检查来自fscanf
. 此函数返回成功转换的次数,可能小于格式字符串中指定的转换次数。
在您的情况下,这可能意味着在第二次调用时可能没有执行任何转换fscanf
,因为文件中的数据格式不正确等。由于没有读取数据,文件句柄没有前进,所以没有到达文件结尾,这反过来又解释了为什么循环不会终止。由于没有读取数据,因此在每次循环迭代中都会打印先前的值。