C Input & Output
When we mentionInputinput, it means feeding some data into the program. Input can be in the form of a file or from the command line. C provides a series of built-in functions to read the given input and feed it into the program as needed.
When we mentionOutputoutput, it means displaying some data on the screen, on a printer, or in any file. C provides a series of built-in functions to output data to the computer screen and save data to text or binary files.
Standard files
C 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 when a program executes, to provide access to the keyboard and screen.
| Standard files | 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 explains how to read values from the keyboard and how to output results to the screen.
I/O (input/output) in C typically uses the two functions printf() and scanf().
The scanf() function reads and formats input from standard input (the keyboard), while the printf() function sends formatted output to standard output (the screen).
The 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: The format string, which specifies the output format. -
...: A variable argument list that provides the data to be output according to the format specifiers in the format string.
Example
#include
<
stdio.h
// This library is required to execute the printf() function
int
main
(
)
{
printf
(
"
Runoob Tutorial
"
)
;
// Display the content inside the quotes
return
0
;
}
Compile the above program; the output is:
Runoob Tutorial
Example analysis:
- Every C program needs to include the main() function. Code begins executing from the main() function.
- printf() Used for formatted output to the screen.printf() The function is declared in the "stdio.h" header file.
- stdio.h is a header file (standard input/output header) and #include is a preprocessor directive used to include header files. When the compiler encounters the printf() function, if the stdio.h header file is not found, a compilation error occurs.
- return 0; The statement is used to indicate exiting the program.
%d formats an integer for output
#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 the printf() function to match the integer variable testInteger and output it to the screen.
%f formats floating-point data for output
#include
<
stdio.h
int
main
(
)
{
float
f;
printf
(
"
Enter a number:
"
)
;
// %f matches floating-point data
scanf
(
"
%f
"
,&
f
)
;
printf
(
"
Value = %f
"
,
f
)
;
return
0
;
}
The 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: The format string, which specifies the format of the input. -
...: A variable argument list that provides the addresses of variables where the input data is stored, according to the format specifiers in the format string.
Example
#include
int
main
(
)
{
int
a
;
float
b
;
printf
(
"Enter an integer and a float: "
)
;
scanf
(
"%d %f"
,
&
a
,
&
b
)
;
printf
(
"You entered: %d and %.2f\n"
,
a
,
b
)
;
return
0
;
}
Execute the above code, then enter:
10 3.14
Output:
You entered: 10 and 3.14
Character input and output
The getchar() & putchar() functions
int getchar(void) The function 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) The function outputs a 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.
Please look at 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 enter some text. When you enter text and press Enter, the program continues and reads only a single character, displayed as follows:
$./a.out
Enter a value :runoob
You entered: r
String input and output
The gets() and fgets() functions
The gets() function is used to read a line of string from the standard input device, but it is not recommended because it can easily cause buffer overflows; the fgets() function is recommended instead.
Syntax:
char *fgets(char *str, int n, FILE *stream);
Parameters:
-
str: A pointer to a character array used to store the string read. -
n: The maximum number of characters to read (including the null character\0). -
stream: The file stream, usually usingstdinto represent standard input.
Example
#include
int
main
(
)
{
char
str
[
100
]
;
printf
(
"Enter a string: "
)
;
fgets
(
str
,
sizeof
(
str
)
,
stdin
)
;
printf
(
"You entered: %s"
,
str
)
;
return
0
;
}
The 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 be output.
Return Value:
-
Returns a nonnegative value on success, or
EOF.
Example
#include
int
main
(
)
{
char
str
[
]
=
"Hello, World!"
;
puts
(
str
)
;
return
0
;
}
Output:
Hello, World!
The 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 be output (a character array terminated by the null character\0). -
stream: The stream specifying the output, which can be standard output (stdout), a file stream, etc.
Return Value:
-
Returns a nonnegative value on success (usually the number of characters output).
-
On failure, returns
EOF.
Characteristics:
-
No newline added:
fputs()Does not automatically add a newline character after the output string. -
Flexible output stream:
fputs()Can output to any stream, such as standard output, files, etc.
Example
#include
int
main
(
)
{
char
str
[
]
=
"Hello, World!"
;
fputs
(
str
,
stdout
)
;
// Output "Hello, World!" without a newline
return
0
;
}
The difference between puts() and fputs()
| Feature | puts() |
fputs() |
|---|---|---|
| Newline | Automatically adds a newline character at the end of the string | No newline added |
| Output stream | Can only output to standard output (the screen) | Can output to any stream (such as a file or the screen) |
| Parameters | Requires only one string argument | Requires a string argument and a stream argument |
| Return Value | Returns a nonnegative value on success, or EOF |
Returns a nonnegative value on success, or EOF |
The scanf() and printf() functions
*int scanf(const char format, ...) The function reads input from the standard input stream stdin and scans the input according to the provided format format.
*int printf(const char format, ...) The function writes output to the standard output stream **stdout ** and produces output according to the provided format.
format It 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 you can use as needed. For full details, you can refer to the reference manual for these functions. Now let's deepen our understanding with the following simple example:
Example
#include
<
stdio.h
int
main
(
)
{
char
str
[
100
];
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 enter some text. When you enter text and press Enter, the program continues and reads the input, displayed as follows:
$./a.out
Enter a value :runoob 123
You entered: runoob 123
Here, it should be pointed out that scanf() expects the input format to match the %s and %d you provided, which means you must provide valid input such as "string integer". If you provide "string string" or "integer integer", it will be considered invalid input. Also, when reading a string, scanf() stops reading as soon as it encounters a space, so "this is test" is three strings to scanf().
File input and output
C also provides file input and output capabilities, allowing data to be read from or written to files.
The 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 in which to open the file, such as"r"(read-only),"w"(write-only),"a"(append), etc.
Return Value:
-
On success, returns a pointer to the
FILEobject; on failure, returnsNULL.
The fclose() function
The fclose() function is used to close an open file.
Syntax:
int fclose(FILE *stream);
Parameters:
-
stream: A pointer to theFILEobjects.
Return Value:
-
On success, it returns
0, returns on failureEOF.
Example
#include
int
main
(
)
{
FILE
file
;
file
=
fopen
(
"example.txt"
,
"w"
)
;
if
(
file
!=
NULL
)
{
fprintf
(
file
,
"Hello, world!\n"
)
;
fclose
(
file
)
;
}
char
buffer
[
100
]
;
file
=
fopen
(
"example.txt"
,
"r"
)
;
if
(
file
!=
NULL
)
{
fgets
(
buffer
,
sizeof
(
buffer
)
,
file
)
;
// Read an entire line
printf
(
"Read from file: %s"
,
buffer
)
;
// fgets preserves the newline character
fclose
(
file
)
;
}
return
0
;
}
Output:
Read from file: Hello, world!