graph TD
A[Input Strategy] --> B{Input Mode}
B -->|Blocking| C[Wait for Complete Input]
B -->|Non-Blocking| D[Immediate Response]
Method |
Description |
Use Case |
fgets() |
Reads entire line |
Safe string input |
scanf() |
Formatted input |
Structured data |
getline() |
Dynamic memory allocation |
Variable-length input |
#include <stdio.h>
#include <string.h>
#define MAX_INPUT 100
int main() {
char buffer[MAX_INPUT];
// Safe input with fgets()
printf("Enter your name: ");
if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
// Remove trailing newline
buffer[strcspn(buffer, "\n")] = 0;
printf("Hello, %s!\n", buffer);
}
return 0;
}
Using select() for Timeout
#include <stdio.h>
#include <sys/select.h>
#include <sys/time.h>
int is_input_available(int seconds) {
fd_set readfds;
struct timeval timeout;
FD_ZERO(&readfds);
FD_SET(STDIN_FILENO, &readfds);
timeout.tv_sec = seconds;
timeout.tv_usec = 0;
return select(STDIN_FILENO + 1, &readfds, NULL, NULL, &timeout);
}
int validate_input(char *input) {
// Custom validation logic
if (strlen(input) < 3) {
printf("Input too short!\n");
return 0;
}
return 1;
}
2. Error Handling Strategies
#include <errno.h>
void handle_input_error() {
if (feof(stdin)) {
printf("End of input reached\n");
} else if (ferror(stdin)) {
printf("Input error: %s\n", strerror(errno));
}
}
- Use appropriate buffer sizes
- Implement input validation
- Handle potential buffer overflows
- Choose efficient input methods
At LabEx, we emphasize the importance of robust input handling to create reliable and secure C applications.