It is indeed a weird thing to do because it doesn't help. Whether fseek
works or not isn't affected by the name of the variable used as an argument.
It can succeed if the handle is for a plain file.
It can't succeed if the handle isn't for a plain file.
This is true for fseek(stdin, ...)
. (Code below.)
$ ./fseek_stdin <file
fghij
$ cat file | ./fseek_stdin
fseek: Illegal seek
This is true for fseek(f, ...)
. (Code below.)
$ ./fseek_f <file
fghij
$ cat file | ./fseek_f
fseek: Illegal seek
But there is also no harm in assigning stdin
to another variable. For example, you might do
FILE *f;
if (...) {
f = stdin;
} else {
f = fopen(...);
}
Or you might do
void some_func(FILE *f) {
...
}
some_func(stdin);
These are both perfectly legitimate assignments of stdin
to another variable.
Here are the files used in the earlier tests:
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;
}
A diff of the two programs (slightly massaged for readability):
$ 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;
} }