将指针重置为文件的开头

Kyu*_*yuu 17 c string pointers

我怎样才能重置指向命令行输入或文件开头的指针.例如,我的函数是从文件中读取一行并使用getchar()将其打印出来

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

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

即我输入(./function <inputs.txt)

R S*_*ahu 33

如果您有FILE*其他人stdin,您可以使用:

rewind(fptr);
Run Code Online (Sandbox Code Playgroud)

要么

fseek(fptr, 0, SEEK_SET);
Run Code Online (Sandbox Code Playgroud)

将指针重置为文件的开头.

你不能这样做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;
}
Run Code Online (Sandbox Code Playgroud)

  • 考虑使用fseek而不是倒带,因为只有fseek提供了错误检查的返回码:https://www.geeksforgeeks.org/g-fact-82/ (2认同)

pad*_*ddy 5

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

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