Non-Standard I/O Functions in C
While the C standard library provides robust functions for input/output operations, many C implementations include non-standard I/O functions that offer additional functionality or convenience that are not covered by the ANSI C specification.
The non-standard functions may not come bundled with every C compiler. We may need to install the relevant library manually to use them. Following are some commonly used non-standard Input and Output function in C:
1. getch() and getche()
These functions are the part of conio.h library for windows. They are used to read a single character from the keyboard without waiting for a newline.
Syntax
ch = getch();
ch = getche();
This function does not take any parameters. It returns the ASCII value of the pressed key (as an int). The getch() function does not echo the character to the console, while getche() does.
Example
#include <conio.h>
#include <stdio.h>
int main() {
printf("Press a key (not echoed): ");
int ch = getch();
printf("\nYou pressed: %c\n", ch);
printf("Press a key (echoed): ");
ch = getche();
printf("\nYou pressed: %c\n", ch);
return 0;
}
Output
Press a key (not echoed): pressed E
You pressed: E
Press a key (echoed): pressed E
E
You pressed:E
2. kbhit
The kbhit() function checks if a key has been pressed without blocking. It is also the part of conio.h header file.
Syntax
kbhit();
This function does not take any parameter and return a non-zero if a key is available, zero otherwise.
Example
#include <conio.h>
#include <stdio.h>
int main() {
printf("Press any key to continue, or wait...\n");
while (!kbhit()) {
printf("Waiting...\n");
// Non-standard sleep, discussed later
sleep(1);
}
printf("Key pressed: %c\n", getch());
return 0;
}
Output
Press any key to continue, or wait...
Waiting...
Waiting...
Key pressed: f
3. clrscr()
Also the part of conio.h library, this function is used to clear the console screen. It is exclusive to windows systems.
Syntax
clrscr();
This function neither take any parameter nor returns any value.
Example
#include <conio.h>
#include <stdio.h>
int main() {
printf("Screen will clear in 2 seconds...\n");
sleep(2);
clrscr();
printf("Screen cleared!\n");
return 0;
}
Output (Before clrscr())
Screen will clear in 2 seconds...
Output (After 2 seconds)
Screen Cleared
4. gets_s()
The gets_s() is a safer alternative to the deprecated gets, reading a line into a buffer with a size limit. It is optional and is defined inside stdio.h header file if defined.
Syntax
gets_s(buff, size);
where,
- buff: string buffer where input is stored.
- size: Number of characters to read.
Example
#include <stdio.h>
int main() {
char str[20];
if (gets_s(str, sizeof(str)) != NULL) {
printf("Read: %s\n", str);
} else {
printf("Input error\n");
}
return 0;
}
Output
This is input string for testing
Read: This is input string