Input and output function: enables programs to interact with users or files.
Header file: #include<>
1. printf function: output format information to the console 💬
🔧Using format
printf("Format string", Parameter list);
🎯 Function
Output the formatted string to the console. The format string can contain ordinary characters and format specifiers, and the format specifier will be replaced by the value in the parameter list afterwards.
📖 Usage
The format specifier is generally%
The beginning, the common ones are%d
(for output integers),%f
(for output floating point numbers),%c
(for output characters),%s
(used to output strings) etc.
⚠️ Notes
- The format specifier should match the type of the parameter.
- Normal characters in the format string will be output as is.
📌 Applicable Type
Suitable for various basic data types as well as strings.
💡 Example
#include <> int main() { int age = 20; float height = 1.75; char grade = 'A'; char name[] = "Alice"; // Output integer printf("Age is %d years old.\n", age); // Output floating point number printf("Height is %.2f meters.\n", height); // Output characters printf("The grade level is %c.\n", grade); // Output string printf("The name is %s.\n", name); return 0; }
🌟 Explain
In this example,printf
The function outputs the value of the variable to the console according to the format specifier.%.2f
Indicates that two decimal places are retained when outputting floating point numbers.
2. scanf function: read formatted input from the console 📥
🔧Using format
scanf("Format string", &variable1, &variable2, ...);
🎯 Function
Read the data entered by the user from the console and store the data in the corresponding variable according to the requirements of the format string.
📖 Usage
Format specifier andprintf
Similar in functions, but the address character must be added before the variable name.&
, to indicate that the data is to be stored at the address of the variable.
⚠️ Notes
- The input data must match the format string.
- When entering multiple data, it is generally separated by spaces, tabs or newlines.
📌 Applicable Type
Suitable for various basic data types.
💡 Example
#include <> int main() { int num; float score; char ch; // Prompt the user to enter integer printf("Please enter an integer:"); scanf("%d", &num); // Prompt the user to enter a floating point number printf("Please enter a floating point number:"); scanf("%f", &score); // Prompt the user to enter characters printf("Please enter a character:"); scanf(" %c", &ch); // Note the spaces in front, which are used to skip the line breaks entered before // Output the content input by the user printf("The integer you enter is %d, the floating point number is %.2f, and the character is %c.\n", num, score, ch); return 0; }
🌟 Explain
In this example,scanf
The function reads the user input data according to the format specifier and stores them in the corresponding variables. Adding spaces before reading characters is to skip the line breaks entered before.
3. getchar function: read a single character ⌨️
🔧Using format
int getchar(void);
🎯 Function
Read a character from standard input (usually a keyboard) and return the ASCII code value of that character.
📖 Usage
Callgetchar
When the function is used, the program will pause and wait for the user to enter a character. After pressing the Enter key, the function will return the ASCII code value of the character.
⚠️ Notes
-
getchar
It can read newline characters, so you should pay attention to handling newline characters when using them continuously. - The function return value is
int
Type, notchar
type.
📌 Applicable Type
Applicable to character types.
💡 Example
#include <> int main() { char ch; // Prompt the user to enter a character printf("Please enter a character:"); ch = getchar(); // Output the characters entered by the user printf("The character you entered is %c.\n", ch); return 0; }
🌟 Explain
In this example,getchar
The function reads a character entered by the user and assigns it to a variablech
, and then output the character.
4. putchar function: output a single character 🖨️
🔧Using format
int putchar(int c);
🎯 Function
Output a character to standard output (usually the console).
📖 Usage
Pass an ASCII code value or character constant of a character, and the function will output the corresponding character to the console.
⚠️ Notes
- The passed parameters can be character constants or ASCII code values of character variables.
- The function returns the ASCII code value of the output character.
📌 Applicable Type
Applicable to character types.
💡 Example
#include <> int main() { char ch = 'B'; // Output characters putchar(ch); putchar('\n'); // Output line breaks return 0; }
🌟 Explain
In this example,putchar
Functions to characterB
Output to the console and output a newline character.
5. fopen function: open the file 📂
🔧Using format
FILE *fopen(const char *filename, const char *mode);
🎯 Function
Open a file with the specified file name and return a pointer to the fileFILE
Pointer.
📖 Usage
filename
It is the name of the file to be opened.mode
It is a mode for opening files. Common modes include:
-
"r"
: Open the file in read-only mode. -
"w"
: Open the file in write mode, create it if the file does not exist, and clear the content if it exists. -
"a"
: Open the file in append mode, and create it if the file does not exist.
⚠️ Notes
- After opening the file, check whether the returned pointer is
NULL
, ifNULL
It means that the file is opened failed. - After operating the file, use
fclose
Function closes the file.
📌 Applicable Type
Suitable for file operations.
💡 Example
#include <> int main() { FILE *file; // Open the file in read-only mode file = fopen("", "r"); if (file == NULL) { // Output error message printf("Cannot open the file!\n"); return 1; } // File reading operations can be performed here // Close the file fclose(file); return 0; }
🌟 Explain
In this example,fopen
The function tries to open in read-only modeIf the file is opened, an error message will be output. After the file is opened successfully, the file can be read. Finally, use
fclose
Function closes the file.
6. fclose function: close the file ❌
🔧Using format
int fclose(FILE *stream);
🎯 Function
Close the specified file stream and release the relevant resources.
📖 Usage
Pass in a pointerFILE
A pointer of type, which is passedfopen
The function returns.
⚠️ Notes
- After closing the file, you can no longer read and write the file.
- A function return value of 0 indicates that the closing is successful, and non-0 indicates that the closing is failed.
📌 Applicable Type
Suitable for file operations.
💡 Example
#include <> int main() { FILE *file; // Open the file in write mode file = fopen("", "w"); if (file == NULL) { // Output error message printf("Cannot open the file!\n"); return 1; } // File writing operations can be performed here // Close the file if (fclose(file) == 0) { printf("File close successfully!\n"); } else { printf("File closing failed!\n"); } return 0; }
🌟 Explain
In this example,fopen
The function is opened in write modeFile, after file writing operation, use
fclose
The function closes the file and judges whether the closing is successful based on the return value.
7. fgets function: safely read strings 📃
🔧Using format
char *fgets(char *str, int n, FILE *stream);
🎯 Function
Read a line of string from the specified file stream and store it tostr
pointing to the character array.
📖 Usage
str
is a character array that stores read strings.n
is the maximum number of characters to read (including line breaks and string ending characters'\0'
),stream
It is a file stream pointer, which can bestdin
(standard input) or viafopen
Open file pointer.
⚠️ Notes
- If the number of characters read reaches
n - 1
Or when encountering a newline, the reading will stop and will be added at the end of the string.'\0'
。 - If the reading is successful, return
str
Pointer; if the file ending character or error occurs, returnNULL
。
📌 Applicable Type
Applicable to string types.
💡 Example
#include <> int main() { char buffer[100]; // Read a line of string from standard input printf("Please enter a string:"); fgets(buffer, sizeof(buffer), stdin); // Output the read string printf("The string you entered is: %s", buffer); return 0; }
🌟 Explain
In this example,fgets
Functions read a line of string from standard input, at mostsizeof(buffer) - 1
character and then store it tobuffer
In the array and output the string.
8. fputs function: output string to file 📤
🔧Using format
int fputs(const char *str, FILE *stream);
🎯 Function
Put stringstr
Output to the specified file stream.
📖 Usage
str
is the string to be output,stream
It is a file stream pointer, which can bestdout
(standard output) or viafopen
Open file pointer.
⚠️ Notes
- The function will not automatically add newline characters. If a newline is required, add it manually in the string.
'\n'
。 - If the output is successful, return a non-negative value; if an error occurs, return
EOF
。
📌 Applicable Type
Applicable to string types.
💡 Example
#include <> int main() { FILE *file; // Open the file in write mode file = fopen("", "w"); if (file == NULL) { // Output error message printf("Cannot open the file!\n"); return 1; } // Write strings to the file fputs("Hello, World!\n", file); // Close the file fclose(file); return 0; }
🌟 Explain
In this example,fopen
The function is opened in write modedocument,
fputs
Functions put strings"Hello, World!\n"
Write to the file and finally usefclose
Function closes the file.
Buffer management skills
General clearing solution:
void clear_buffer() { int c; while ((c = getchar()) != '\n' && c != EOF); }
Use scenarios:
existscanf()
Call it immediately afterward
When handling exception input
💡 Golden Rule:
- All input functions must consider the risk of buffer overflow
- After the file operation, you must check the return value and close the file
- Format IO must strictly match the type
By mastering these core functions, your C language IO operation will be easy! 🎯
This is the article about the explanation of C language input and output library functions. For more related C language input and output library functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!