SrcForge

Lesson 17

I/O Functions

Input/Output (I/O) functions in C are built-in library functions that allow a program to communicate with users or external devices, provided primarily through the <stdio.h> header file.

C Track

Save progress as you learn.

44 lessons

Lesson content

I/O Functions in C Programming: A Complete Beginner to Advanced Guide

What are I/O Functions in C Programming?

Input/Output (I/O) functions in C are built-in library functions that allow a program to communicate with users or external devices. Input functions read data into a program, while output functions display or write data from the program.

For example:

  • Reading a user's name from the keyboard
  • Displaying a calculation result on the screen
  • Reading data from a file
  • Writing information to a file

In C, most standard I/O functions are provided by the <stdio.h> (Standard Input/Output) header file.

Why Do I/O Functions Exist?

A program without input or output is isolated—it cannot receive information or display results. I/O functions solve this problem by enabling interaction between the program and users, files, and devices.

They help you:

  • Accept user input
  • Display messages and results
  • Read and write files
  • Debug programs using printed output
  • Exchange data with external systems

Real-World Use Cases

I/O functions are used in almost every C application, including:

  • ATM and banking software
  • Student management systems
  • Calculator applications
  • Inventory management
  • Login systems
  • File processing programs
  • Data logging applications

Prerequisites

Before learning I/O Functions in C Programming, you should understand:

  • Variables and data types
  • Operators
  • Strings
  • Functions
  • Basic C program structure
  • Header files

Core Concepts of I/O Functions in C Programming

The <stdio.h> Header File

To use standard I/O functions, include:

#include <stdio.h>

This header provides functions such as:

  • printf()
  • scanf()
  • getchar()
  • putchar()
  • fgets()
  • puts()

Standard Input, Output, and Error

C defines three standard streams:

StreamPurposeDevice
stdinStandard inputKeyboard
stdoutStandard outputScreen
stderrStandard errorScreen (or redirected output)

Output Functions

1. printf()

The printf() function displays formatted output on the screen.

Syntax

printf("format string", arguments);

Example

printf("Age = %d", age);

Common format specifiers:

SpecifierData Type
%dInteger
%fFloat
%lfDouble
%cCharacter
%sString
%xHexadecimal
%oOctal

2. puts()

The puts() function prints a string followed by a newline.

puts("Welcome to C!");

Output: Welcome to C!

3. putchar()

The putchar() function prints a single character.

putchar('A');

Output: A

Input Functions

1. scanf()

The scanf() function reads formatted input from the keyboard.

Syntax

scanf("format", &variable);

Example

scanf("%d", &age);

Note: The address-of operator (&) is required for most variables, except when reading into a character array (string).

2. getchar()

Reads one character from the keyboard.

char ch = getchar();

3. fgets()

Reads an entire line of text, including spaces.

Syntax

fgets(string, size, stdin);

Example

fgets(name, sizeof(name), stdin);

Unlike scanf("%s"), fgets() can read spaces safely.

Formatted vs Unformatted I/O

Formatted I/OUnformatted I/O
printf()putchar()
scanf()getchar()
Uses format specifiersReads or writes raw characters or strings
More flexibleSimpler for character-based operations

Code Examples

Example 1: Beginner – Display Output Using printf()

#include <stdio.h>                     // Include standard input/output library

int main(void)                         // Program entry point
{
    printf("Hello, World!\n");         // Print a message to the screen

    printf("Welcome to C Programming.\n"); // Print another message

    return 0;                          // Indicate successful execution
}

Output: Hello, World! / Welcome to C Programming.

Example 2: Beginner – Read an Integer Using scanf()

#include <stdio.h>                     // Include standard input/output library

int main(void)                         // Program entry point
{
    int age;                           // Declare an integer variable

    printf("Enter your age: ");        // Prompt the user

    scanf("%d", &age);                 // Read an integer from the keyboard

    printf("You entered %d\n", age);   // Display the entered value

    return 0;                          // End the program
}

Example 3: Intermediate – Read a String Using fgets()

#include <stdio.h>                     // Include standard input/output library

int main(void)                         // Program entry point
{
    char name[50];                     // Create a character array

    printf("Enter your full name: ");  // Prompt the user

    fgets(name, sizeof(name), stdin);  // Read a line of text safely

    printf("Hello, %s", name);         // Display the entered string

    return 0;                          // End the program
}

Example 4: Intermediate – Character Input and Output

#include <stdio.h>                     // Include standard input/output library

int main(void)                         // Program entry point
{
    char ch;                           // Declare a character variable

    printf("Enter a character: ");     // Prompt the user

    ch = getchar();                    // Read a single character

    printf("You entered: ");           // Print a label

    putchar(ch);                       // Display the character

    printf("\n");                      // Move to the next line

    return 0;                          // End the program
}

Example 5: Advanced – Read Student Details

#include <stdio.h>                     // Include standard input/output library

int main(void)                         // Program entry point
{
    int rollNo;                        // Store the student's roll number
    float marks;                       // Store the student's marks
    char name[50];                     // Store the student's name

    printf("Enter roll number: ");     // Prompt for roll number
    scanf("%d", &rollNo);              // Read the roll number

    getchar();                         // Consume the newline left by scanf()

    printf("Enter name: ");            // Prompt for the student's name
    fgets(name, sizeof(name), stdin);  // Read the full name

    printf("Enter marks: ");           // Prompt for marks
    scanf("%f", &marks);               // Read the marks

    printf("\nStudent Details\n");     // Print a heading
    printf("Roll No : %d\n", rollNo);  // Display the roll number
    printf("Name    : %s", name);      // Display the name
    printf("Marks   : %.2f\n", marks); // Display the marks

    return 0;                          // End the program
}

Common Mistakes and Pitfalls

WrongCorrect
scanf("%d", age);scanf("%d", &age);
scanf("%s", name); for full namesfgets(name, sizeof(name), stdin);
Ignoring leftover newline after scanf()Consume it with getchar() before calling fgets()
Using the wrong format specifierMatch the specifier to the variable type
Using gets()Use fgets() instead (gets() has been removed from the C standard due to safety issues)

Wrong:

int age;

scanf("%d", age);

Correct:

int age;

scanf("%d", &age);

Best Practices

  • Always include <stdio.h> when using standard I/O functions.
  • Use fgets() instead of gets() for reading strings.
  • Match format specifiers with the correct data types.
  • Check the return value of scanf() to ensure input was read successfully.
  • Be careful when mixing scanf() and fgets() because of leftover newline characters.
  • Use meaningful prompts to guide users during input.
  • Format output neatly for better readability.

When NOT to Use This

Avoid relying solely on standard console I/O when:

  • Building graphical user interface (GUI) applications.
  • Processing very large files where specialized buffered I/O may be more efficient.
  • Developing network applications that require socket-based communication.
  • Writing embedded systems that interact directly with hardware instead of the console.

In such cases, use the appropriate libraries or APIs designed for those environments.

Summary / Key Takeaways

  • I/O Functions in C Programming enable communication between programs and users.
  • Include <stdio.h> to access standard I/O functions.
  • printf() displays formatted output.
  • scanf() reads formatted input.
  • puts() prints a string followed by a newline.
  • putchar() outputs a single character.
  • getchar() reads one character.
  • fgets() is the preferred way to read strings containing spaces.
  • Always use the correct format specifiers and provide addresses to scanf() where required.
  • Handle leftover newline characters when combining scanf() and fgets().

FAQ About I/O Functions in C

1. What is the difference between printf() and puts()?

printf() prints formatted output using format specifiers, while puts() prints a string followed automatically by a newline.

2. Why is & required in scanf()?

scanf() needs the memory address of a variable so it can store the input value. Character arrays (strings) are an exception because the array name already represents its address.

3. Why is fgets() preferred over scanf("%s")?

fgets() can read spaces and limits the number of characters read, helping prevent buffer overflows.

4. Why does fgets() sometimes appear to skip input after scanf()?

scanf() often leaves the newline character ('\n') in the input buffer. A subsequent fgets() reads that newline immediately. Calling getchar() to consume the leftover newline before fgets() resolves this issue.

5. What is the difference between formatted and unformatted I/O?

Formatted I/O (printf(), scanf()) uses format specifiers to read and display different data types, while unformatted I/O (getchar(), putchar(), puts()) works directly with characters or strings without format specifiers.