【问题标题】:Resetting pointer to the start of file重置指向文件开头的指针
【发布时间】:2015-11-28 18:13:19
【问题描述】:

我如何能够重置指向命令行输入或文件开头的指针。例如,我的函数正在从文件中读取一行并使用 getchar() 打印出来

    while((c=getchar())!=EOF)
    {
        key[i++]=c;
        if(c == '\n' )
        {
            key[i-1] = '\0'
            printf("%s",key);
        }       
    }

运行后,指针指向 EOF 我假设?我如何让它再次指向文件的开头/甚至重新读取输入文件

我将其输入为 (./function

【问题讨论】:

  • 关闭并重新打开文件
  • EOF 应该是通过stdin 所以你想重置什么.. 如果你从文件中获取输入然后rewind(fp) 会工作

标签: c string pointers


【解决方案1】:

如果你有一个FILE* 不是stdin,你可以使用:

rewind(fptr);

fseek(fptr, 0, SEEK_SET);

重置指向文件开头的指针。

stdin 不能这样做。

如果您需要能够重置指针,请将文件作为参数传递给程序并使用fopen 打开文件并读取其内容。

int main(int argc, char** argv)
{
   int c;
   FILE* fptr;

   if ( argc < 2 )
   {
      fprintf(stderr, "Usage: program filename\n");
      return EXIT_FAILURE;
   }

   fptr = fopen(argv[1], "r");
   if ( fptr == NULL )
   {
      fprintf(stderr, "Unable to open file %s\n", argv[1]);
      return EXIT_FAILURE;
   }

    while((c=fgetc(fptr))!=EOF)
    {
       // Process the input
       // ....
    }

    // Move the file pointer to the start.
    fseek(fptr, 0, SEEK_SET);

    // Read the contents of the file again.
    // ...

    fclose(fptr);

    return EXIT_SUCCESS;
}

【讨论】:

【解决方案2】:

管道/重定向输入不能这样工作。您的选择是:

  • 将输入读入内部缓冲区(您似乎已经这样做了);或
  • 将文件名作为命令行参数传递,并随心所欲地使用它。

【讨论】:

    猜你喜欢
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 2017-02-05
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多