File or Console Input
C
Hard
4 views
Problem Description
As soon as the program starts, check whether the input is coming from a file (redirected) or from the keyboard. If it is from a file, then give a "Reading from file..." message, otherwise give an "Enter data:" prompt.
Official Solution
#include <stdio.h>
#include <unistd.h> // for isatty()
int main() {
if (isatty(fileno(stdin))) {
// Input is from keyboard
printf("Enter data:n");
} else {
// Input is redirected from a file or pipe
printf("Reading from file...n");
}
/* Example: read and echo input */
char buffer[100];
while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
printf("%s", buffer);
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!