重置指向文件开头的指针 [英] Resetting pointer to the start of file

查看:136
本文介绍了重置指向文件开头的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将指针重置为命令行输入或文件的开头.例如,我的功能是从文件中读取一行,并使用getchar()打印出来

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()

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

运行此命令后,指针将指向EOF im假设?我如何使其再次指向文件的开头/甚至重新读取输入文件

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

我将其输入为(./function< inputs.txt)

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

推荐答案

如果您使用的不是stdinFILE*,则可以使用:

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

rewind(fptr);

fseek(fptr, 0, SEEK_SET);

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

to reset the pointer to the start of the file.

您不能为stdin进行此操作.

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

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

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

这篇关于重置指向文件开头的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆