C语言 重置指向文件开头的指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32366665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 12:06:05  来源:igfitidea点击:

Resetting pointer to the start of file

cstringpointers

提问by Kyuu

How would I be able to reset a pointer to the start of a commandline input or file. For example my function is reading in a line from a file and prints it out using getchar()

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

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

After running this, the pointer is pointing to EOF im assuming? How would I get it to point to the start of the file again/or even re read the input file

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

im entering it as (./function < inputs.txt)

我输入它作为(./function <inputs.txt)

回答by R Sahu

If you have a FILE*other than stdin, you can use:

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

fseek(fptr, 0, SEEK_SET);

or

或者

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;
}

to reset the pointer to the start of the file.

将指针重置到文件的开头。

You cannot do that for stdin.

你不能为stdin.

If you need to be able to reset the pointer, pass the file as an argument to the program and use fopento open the file and read its contents.

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

##代码##

回答by paddy

Piped / redirected input doesn't work like that. Your options are:

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

  • Read the input into an internal buffer (which you already seem to be doing); or
  • Pass the file name as a command-line argument instead, and do with it as you please.
  • 将输入读入内部缓冲区(您似乎已经在做);或者
  • 而是将文件名作为命令行参数传递,并随心所欲地使用它。