重置指向文件开头的指针 [英] Resetting pointer to the start of file
问题描述
如何将指针重置为命令行输入或文件的开头.例如,我的功能是从文件中读取一行,并使用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)
推荐答案
如果您使用的不是stdin
的FILE*
,则可以使用:
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屋!