这确实是一件奇怪的事情,因为它没有帮助。 fseek 是否有效不受用作参数的变量名称的影响。
如果句柄是普通文件,它可以成功。
如果句柄不是用于普通文件,则无法成功。
fseek(stdin, ...) 也是如此。 (代码如下。)
$ ./fseek_stdin <file
fghij
$ cat file | ./fseek_stdin
fseek: Illegal seek
fseek(f, ...) 也是如此。 (代码如下。)
$ ./fseek_f <file
fghij
$ cat file | ./fseek_f
fseek: Illegal seek
但是将stdin 分配给另一个变量也没有坏处。例如,您可能会这样做
FILE *f;
if (...) {
f = stdin;
} else {
f = fopen(...);
}
或者你可以这样做
void some_func(FILE *f) {
...
}
some_func(stdin);
这些都是将stdin 完全合法地分配给另一个变量。
以下是早期测试中使用的文件:
file:
abcdefghij
fseek_stdin.c:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
if (fseek(stdin, 5, SEEK_CUR) < 0) {
perror("fseek");
return EXIT_FAILURE;
}
char *line = NULL;
size_t n = 0;
if (getline(&line, &n, stdin) < 0) {
perror("getline");
free(line);
return EXIT_FAILURE;
}
printf("%s", line);
free(line);
return EXIT_SUCCESS;
}
fseek_f.c:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *f = stdin;
if (fseek(f, 5, SEEK_CUR) < 0) {
perror("fseek");
return EXIT_FAILURE;
}
char *line = NULL;
size_t n = 0;
if (getline(&line, &n, f) < 0) {
perror("getline");
free(line);
return EXIT_FAILURE;
}
printf("%s", line);
free(line);
return EXIT_SUCCESS;
}
两个程序的差异(为了便于阅读,略作修饰):
$ diff -y fseek_{stdin,f}.c
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
int main(void) { int main(void) {
> FILE *f = stdin;
>
if (fseek(stdin, 5, SEEK_CUR) < 0) { | if (fseek(f, 5, SEEK_CUR) < 0) {
perror("fseek"); perror("fseek");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
char *line = NULL; char *line = NULL;
size_t n = 0; size_t n = 0;
if (getline(&line, &n, stdin) < 0) { | if (getline(&line, &n, f) < 0) {
perror("getline"); perror("getline");
free(line); free(line);
return EXIT_FAILURE; return EXIT_FAILURE;
} }
printf("%s", line); printf("%s", line);
free(line); free(line);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }