C Input & Output
When we mentionInputWhen, this means to fill some data into the program. Input can be from a file or from the command line. C language provides a series of built-in functions to read given input and fill it into the program as needed.
When we mentionOutputWhen, this means to display some data on the screen, printer, or in any file. C language provides a series of built-in functions to output data to the computer screen and save data to text files or binary files.
standard files
C language treats all devices as files. So devices (such as monitors) are handled in the same way as files. The following three files are automatically opened when the program is executed to access the keyboard and screen.
| standard files | file pointer | devices |
|---|---|---|
| standard input | stdin | keyboard |
| standard output | stdout | screen |
| standard error | stderr | your screen |
A file pointer is a way to access files. 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 language usually usesprintf()andscanf()Two functions.
The scanf() function is used to read and format from standard input (keyboard), and 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: Format string, specifies the format of the output....: Variable argument list, provides the data to be output according to the format specifiers in the format string.
Example
Compile the above program, the output result is:
Example Tutorial
Example Analysis:
- All C language programs need to includemain()Function. The code starts frommain()The function begins execution.
- printf()Used for formatted output to the screen.printf()The function is in"stdio.h"Declared in the header file.
- stdio.his a header file (standard input/output header file) and#includeis a preprocessor command used to include header files. When the compiler encountersprintf()When using the function, if not foundstdio.hheader file, a compilation error will occur.
- return 0;
%d is used to format and output integers.
Compile the above program, the output result is:
Number = 5
Use "%d" (integer) in the quotes of the printf() function to match the integer variable testInteger and output it to the screen.
%f is used to format and output floating-point data.
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: Format string, specifies the format of the input....: Variable argument list, provides the addresses of variables to store the input data based on the format specifiers in the format string.
Example
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/output
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 in 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 in a loop to output multiple characters to the screen.
See the following example:
Example
When the above code is compiled and executed, it waits for you to enter some text. When you enter text and press the Enter key, the program continues and reads only a single character, as shown below:
$./a.out Enter a value :example You entered: r
String input/output
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 lead to buffer overflow. It is recommended to usefgets()function.
Syntax:
char *fgets(char *str, int n, FILE *stream);
Parameters:
str: Pointer to a character array, used to store the read string.n: The maximum number of characters to read (including the null character\0)。stream: file stream, usually usestdinRepresents standard input.
Example
int main() {
char str[100];
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 at the end.
Syntax:
int puts(const char *str);
Parameters:
str: the string to be output.
Return value:
Returns a non-negative value on success, and returns on failure
EOF。
Example
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 at the end of the string.
Syntax:
int fputs(const char *str, FILE *stream);
Parameters:
str: the string to be output (a character array that ends with a null\0character).stream: Specifies the output stream, which can be standard output (stdout), file streams, etc.
Return value:
Returns a non-negative value on success (usually the number of characters output).
Return on failure
EOF。
Features:
Does not add a newline character:
fputs()It does not automatically add a newline after outputting the string.Flexible output stream:
fputs()It can output to any stream, such as standard output, files, etc.
Example
int main() {
char str[] = "Hello, World!";
fputs(str, stdout); // Output "Hello, World!" without newline
return 0;
}
The difference between puts() and fputs()
| Features | puts() | fputs() |
|---|---|---|
| Newline | 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). | It can output to any stream (such as files, screen) |
| Parameter | Only requires one string argument. | Requires a string argument and a stream argument. |
| Return Value | Returns a non-negative value on success, and returns on failureEOF | Returns a non-negative value on success, and returns on failureEOF |
scanf() and printf() functions
int scanf(const char *format, ...)The function reads from the standard input streamstdinreads the input, and according to the providedformatTo browse through the input.
int printf(const char *format, ...)The function writes output to the standard output streamstdout , and generates output according to the provided format.
formatIt can be a simple constant string, but you can specify %s, %d, %c, %f, etc. respectively to output or read strings, integers, characters, or floating-point numbers. There are many other available format options that can be used as needed. For full details, you can refer to the reference manuals of these functions. Now let us deepen our understanding through the following simple example:
Example
When the above code is compiled and executed, it waits for you to enter some text. When you enter text and press the Enter key, the program continues and reads the input, as shown below:
$./a.out Enter a value :example 123 You entered: example 123
Here, it should be noted that scanf() expects the input format to be the same as the %s and %d you provide, which means you must provide valid input, such as "string integer". If you provide "string string" or "integer integer", it will be considered incorrect input. In addition, when reading a string, scanf() stops reading as soon as it encounters a space, so "this is test" is three strings for scanf().
File input and output
C language also provides file input/output capabilities, allowing data to be read from files 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 filename to be opened.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
FILEpointer to the object, and on failure returnsNULL。
fclose() function
The fclose() function is used to close an opened file.
Syntax:
int fclose(FILE *stream);
Parameters:
stream: points toFILEa pointer to the object.
Return value:
returns on success
0, on failure, returnsEOF。
Example
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 retains the newline character
fclose(file);
}
return 0;
}
Output content:
Read from file: Hello, world!other extensions