YouTip LogoYouTip

C Input Output

When we talk about input, it means feeding some data into a program. The input can be in the form of a file or from the command line. C language provides a series of built-in functions to read the given input and fill it into the program as needed.

When we talk about output, it means displaying some data on a screen, a printer, or in any file. C language provides a series of built-in functions to output data to the computer screen and to save data to text files or binary files.

The C language treats all devices as files. Therefore, devices (such as the display) are handled in the same way as files. The following three files are automatically opened during program execution for access to the keyboard and screen.

Standard File File Pointer Device
Standard Input stdin Keyboard
Standard Output stdout Screen
Standard Error stderr Your screen

A file pointer is a way to access a file. This section will explain how to read values from the keyboard and how to output results to the screen.

I/O (Input/Output) in C is typically done using two functions: printf() and scanf().

The scanf() function reads from standard input (keyboard) and formats it. The printf() function sends formatted output to standard output (screen).

printf() Function

The printf() function is used to output formatted data to the standard output device (usually the screen).

Syntax:

int printf(const char *format, ...);

Parameters:

  • format: A format string that specifies the output format.
  • ...: A variable argument list that provides the data to be output based on the format specifiers in the format string.

Example

#include<stdio.h> // Required for the printf() function
int main(){
    printf("");
    return 0;
}

Compile the above program, the output is:

Example Explanation:

  • All C programs need to include a main() function. Code execution starts from the main() function.
  • printf() is used for formatted output to the screen. The printf() function is declared in the "stdio.h" header file.
  • stdio.h is a header file (Standard Input Output header file) and #include is a preprocessor command used to include header files. If the compiler encounters the printf() function without finding the stdio.h header file, a compilation error will occur.
  • The return 0; statement is used to indicate the exit of the program.

%d Formatted Output for Integers

#include<stdio.h>
int main(){
    int testInteger = 5;
    printf("Number = %d", testInteger);
    return 0;
}

Compile the above program, the output is:

Number = 5

Use "%d" (integer) inside the quotes of printf() to match the integer variable testInteger and output it to the screen.

%f Formatted Output for Floating-Point Data

#include<stdio.h>
int main(){
    float f;
    printf("Enter a number: ");
    scanf("%f",&f);
    printf("Value = %f", f);
    return 0;
}

scanf() Function

The scanf() function is used to read formatted input from the standard input device (usually the keyboard).

Syntax:

int scanf(const char *format, ...);

Parameters:

  • format: A format string that specifies the input format.
  • ...: A variable argument list that provides the addresses of variables to store the input data based on the format specifiers in the format string.

Example

#include <stdio.h>

int main(){
    int a;
    float b;
    printf("Enter an integer and a float: ");
    scanf("%d %f",&a,&b);
    printf("You entered: %d and %.2fn", a, b);
    return 0;
}

Execute the above code, then enter:

10 3.14

Output:

You entered: 10 and 3.14

Character Input and Output

getchar() & putchar() Functions

int getchar(void) reads the next available character from the screen and returns it as an integer. This function reads only a single character at a time. You can use this method inside a loop to read multiple characters from the screen.

int putchar(int c) outputs the character to the screen and returns the same character. This function outputs only a single character at a time. You can use this method inside a loop to output multiple characters to the screen.

Consider the following example:

Example

#include<stdio.h>
int main(){
    int c;
    printf("Enter a value :");
    c = getchar();
    printf("nYou entered: ");
    putchar(c);
    printf("n");
    return 0;
}

When the above code is compiled and executed, it waits for you to input some text. When you enter text and press the enter key, the program continues and reads only a single character, displaying:

$./a.out
Enter a value :
You entered: r

gets() and fgets() Functions

The gets() function is used to read a line of string from standard input, but it is not recommended because it can easily cause buffer overflow. The fgets() function is recommended.

Syntax:

char *fgets(char *str, int n, FILE *stream);

Parameters:

  • str: A pointer to a character array to store the read string.
  • n: Maximum number of characters to read (including the null character ).
  • stream: File stream, typically using stdin to represent standard input.

Example

#include <stdio.h>

int main(){
    char str;
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    printf("You entered: %s",str);
    return 0;
}

puts() Function

The puts() function is used to output a string to the standard output device and automatically adds a newline character at the end.

Syntax:

int puts(const char *str);

Parameters:

  • str: The string to output.

Return Value:

  • Returns a non-negative value on success, returns EOF on failure.

Example

#include <stdio.h>

int main(){
    char str[]="Hello, World!";
    puts(str);
    return 0;
}

Output:

Hello, World!

fputs() Function

The fputs() function is used to output a string to a specified stream (such as standard output, a file, etc.), but it does not automatically add a newline character at the end of the string.

Syntax:

int fputs(const char *str, FILE *stream);

Parameters:

  • str: The string to output (a character array ending with a null character ).
  • stream: The specified output stream, which can be standard output (stdout), a file stream, etc.

Return Value:

  • Returns a non-negative value (usually the number of characters output) on success.
  • Returns EOF on failure.

Characteristics:

  1. No Newline Added: fputs() does not automatically add a newline character after outputting the string.
  2. Flexible Output Stream: fputs() can output to any stream, such as standard output, files, etc.

Example

#include <stdio.h>

int main(){
    char str[]="Hello, World!";
    fputs(str, stdout); // Outputs "Hello, World!" without a newline
    return 0;
}

Differences between puts() and fputs()

Feature puts() fputs()
Newline Character Automatically adds a newline character at the end of the string Does not add a newline character
Output Stream Can only output to standard output (screen) Can output to any stream (e.g., file, screen)
Parameters Only requires one string parameter Requires a string parameter and a stream parameter
Return Value Returns a non-negative value on success, EOF on failure Returns a non-negative value on success, EOF on failure

int scanf(const char *format, ...) reads input from the standard input stream stdin and scans the input according to the provided format.

int printf(const char *format, ...) writes output to the standard output stream stdout and produces output according to the provided format.

format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to output or read strings, integers, characters, or floating-point numbers. There are many other format options available that can be used as needed. For complete details, you can consult the reference manual of these functions. Now let's deepen our understanding through this simple example:

Example

#include<stdio.h>
int main(){
    char str;
    int i;
    printf("Enter a value :");
    scanf("%s %d", str, &i);
    printf("nYou entered: %s %d ", str, i);
    printf("n");
    return 0;
}

When the above code is compiled and executed, it waits for you to input some text. When you enter text and press the enter key, the program continues and reads the input, displaying:

$./a.out
Enter a value : 123
You entered:  123

Here, it should be noted that scanf() expects the input format to match the %s and %d you provided. This means you must provide valid input, such as "string integer". If you provide "string string" or "integer integer", it will be considered invalid input. Additionally, when reading a string, scanf() stops reading as soon as it encounters a space, so "this is test" is considered three strings by scanf().


File Input and Output

C also provides file I/O capabilities, allowing data to be read from or written to files.

fopen() Function

The fopen() function is used to open a file.

Syntax:

FILE *fopen(const char *filename, const char *mode);

Parameters:

  • filename: The name of the file to open.
  • mode: The mode for opening the file, such as "r" (read-only), "w" (write-only), "a" (append), etc.

Return Value:

  • Returns a pointer to a FILE object on success, returns NULL on failure.

fclose() Function

The fclose() function is used to close an opened file.

Syntax:

int fclose(FILE *stream);

Parameters:

  • stream: A pointer to a FILE object.

Return Value:

  • Returns 0 on success, returns EOF on failure.

Example

#include <stdio.h>

int main(){
    FILE *file;
    file = fopen("example.txt", "w");
    if(file != NULL){
        fprintf(file, "Hello, world!n");
        fclose(file);
    }
    char buffer;
    file = fopen("example.txt", "r");
    if(file != NULL){
        fgets(buffer, sizeof(buffer), file); // Read the entire line
        printf("Read from file: %s", buffer); // fgets retains the newline character
        fclose(file);
    }
    return 0;
}

Output:

Read from file: Hello, world!
← Html5 SyntaxReact Refs β†’