我如何能够重置指向命令行输入或文件开头的指针。例如,我的函数是从文件中读取一行并使用getchar()
将其打印出来 while((c=getchar())!=EOF)
{
key[i++]=c;
if(c == '\n' )
{
key[i-1] = '\0'
printf("%s",key);
}
}
运行之后,指针指向EOF im假设?如何让它再次指向文件的开头/甚至重新读取输入文件
我输入为(./function< inputs.txt)
答案 0 :(得分:27)
如果您有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;
}
答案 1 :(得分:4)
管道/重定向输入并不像那样工作。您的选择是: