【问题标题】:fseek does not work in linux [duplicate]fseek 在 linux 中不起作用 [重复]
【发布时间】:2012-09-22 06:51:58
【问题描述】:

可能重复:
Using fseek with a file pointer that points to stdin

我有一个程序使用 fseek 来清除我的输入缓冲区,它在 Windows 中运行良好,在 Linux 中 buf 失败。请帮帮我。

#include <stdio.h>
#define NO_USE_FSEEK    0

int main(int argc, char *argv[])
{
   char ch = 'a';
   int i = 1;
   long int fpos = -1;

   while(1)
   {
      printf("loop : %d\n", i);

      fseek(stdin, 0L, SEEK_END); /*works in Windows with MinGW, fails in Linux*/
      fpos = ftell(stdin);
      if (-1 == fpos)
      {
         perror("ftell failure:");   /*perror tells it is Illegal Seek*/
         printf("\n");
      }
      else
      {
         printf("positon indicator:%ld\n", fpos);
      }
      scanf("%c", &ch);
      printf("%d : %c\n", (int)ch, ch);
      i++;

   }

   return 0;
}

提前致谢!

【问题讨论】:

  • 想象stdin 是一个水龙头。显然你想打开水龙头并“寻找”到最后一滴......然后(通过scanf()电话)再挤出一个滴:)

标签: c linux io inputstream fseek


【解决方案1】:

测试fseek()的返回值(其实就是测试所有&lt;stdio.h&gt;输入函数的返回值)。

if (fseek(stdin, 0, SEEK_END) < 0) { perror("fseek"); exit(EXIT_FAILURE); }

使用成语

while ((ch = getchar()) != '\n' && ch != EOF) /* void */;
/* if (ch == EOF)
**     call feof(stdin) or ferror(stdin) if needed; */

忽略输入缓冲区中的所有字符,直到下一个 ENTER(或文件结尾或输入错误)。

【讨论】:

  • 为什么会出错?输入流以 EOF 结束是完全有效的: (b) 当用户在终端输入 EOF 字符时(例如在 Linux 中使用 Ctrl+D 或在 Windows cmd 中使用 AFAIR、Ctrl+Y/Z 时)。
  • @PiotrKalinowski: getchar() 在两种情况下返回 EOF。要识别它,EOF 是由于文件结束条件或某种错误,您需要调用另一个函数(feof()ferror())。当我在回答中说“输入错误”时,我在该组中包含了文件结束条件。现已修复,谢谢。
【解决方案2】:

这不是在 Windows 或 Linux 上“清除输入缓冲区”的公认方式。

在 Windows 上,使用标准 C 函数的 MSVCRT 版本,有一个扩展允许 fflush(stdin) 用于此目的。请注意,在其他系统上,这是未定义的行为。

Linux 有一个名为 fpurge 的函数,目的相同。

但是,我不得不问,为什么你要清除你的输入缓冲区?如果这是人们对 scanf 没有读到行尾的常见抱怨,那么最好编写代码来实际读取并丢弃行的其余部分(循环使用getc,直到读取'\n',例如,如pmg的回答)。当用于重定向文件或管道而不是正常的控制台/tty 输入时,清除输入缓冲区往往会跳过大量数据。

【讨论】:

    【解决方案3】:

    我猜 fseek 不适用于标准输入。因为标准输入的大小是未知的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-12
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多