将指针重置为文件的开头
我怎样才能重置指向命令行输入或文件开头的指针。 例如,我的函数是从文件中读取一行并使用getchar()将其打印出来
while((c=getchar())!=EOF) { key[i++]=c; if(c == '\n' ) { key[i-1] = '\0' printf("%s",key); } }
运行之后,指针指向EOF im假设? 如何让它再次指向文件的开头/甚至重新读取输入文件
即我输入(./function <inputs.txt)
如果你有一个除stdin
之外的FILE*
,你可以使用:
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; }
管道/重定向输入不能像这样工作。 你的选择是:
•将输入读入内部缓冲区(您似乎已经在做); 要么
•将文件名作为命令行参数传递,并根据需要使用它。