C - Non-formatted Input and Output

Non-formatted input and output in C refers to operations where data is read from or written to a stream without applying specific formatting. In these operations, the data is treated as a sequence of characters, and no interpretation of the data's type or structure is performed by default. Here are examples of non-formatted input and output functions in C:

1. getc and putc:

getc reads a character from a stream, and putc writes a character to a stream. These functions work with individual characters.


#include <stdio.h>

int main() {
    int ch;
    printf("Enter a character: ");
    ch = getc(stdin); // Read a character from standard input
    printf("You entered: ");
    putc(ch, stdout); // Write the character to standard output
    return 0;
}

Output (console, user input):


Enter a character: A
You entered: A
2. getchar and putchar:

getchar and putchar are similar to getc and putc, but they work specifically with the standard input and output streams.



int main() {
    int ch;
    printf("Enter a character: ");
    ch = getchar(); // Read a character from standard input
    printf("You entered: ");
    putchar(ch); // Write the character to standard output
    return 0;
}

Output (console, user input):


Enter a character: B
You entered: B
3. gets and puts:

gets reads a line of text from a stream, and puts writes a string followed by a newline character to a stream. These functions work with strings.



int main() {
    char buffer[100];
    printf("Enter a string: ");
    gets(buffer); // Read a string from standard input
    printf("You entered: ");
    puts(buffer); // Write the string to standard output
    return 0;
}

Output (console, user input):


Enter a string: Hello, World!
You entered: Hello, World!

These non-formatted input and output functions are useful when you want to read or write data as a sequence of characters without considering the data's type or structure. However, it's important to use them with caution, as they do not perform any type checking or validation. In modern C programming, using formatted input and output functions (e.g., printf, scanf, fprintf, fscanf) is generally recommended for better safety and control.