Detailed explanation of the fgets() function and some details that need to be paid attention to when using it - C language basics

Insert image description here
What this article will discuss is "Detailed explanation of the fgets() function and some details that need to be paid attention to when using it". Involves the application of the fgets() function and issues that need attention. It belongs to the basics of C language ( 持续更新).

fgets() (Function prototype: char *fgets(char *restrict str, int size, FILE *restrict stream) )

The prototype of this function is not easy to understand. It can be understood as (char *fgets("Container address", "Container size", "Read from where"))


General usage:

char a[100] = {0};
fgets(a, 100, stdin);

In layman's terms, fgets()the function is to read a row of data. But if you want to put it in detail and professionally, fgets()the function of the function can be explained like this:Reads characters up to the size of the second parameter from the stream specified by the third parameter into the container address specified by the first parameter.. In this process, before reading enough characters of the size specified by the second parameter, there 换行符'\n'is no data in the stream that is read or needs to be read. It ends early and stores the characters that have been read into the container address specified by the first parameter.

Under normal circumstances fgets()the return value of a function is the same as its first argument. That is, the container address stored after reading the data. However, if a reading error occurs or the file is empty when reading the file, anull pointer


fgets()The running process of the function is roughly like this:

When the system calls this function, the system will block and wait for the user's input, and will not return to the program until the user enters the carriage return character '\n'. Then the content entered by the user will be put into the input buffer area by the system, and the fgets() function will come in and read its "second parameter minus 1 (why minus 1 will be discussed later)" bytes and store them into its first parameter. In the memory address pointed to, if the newline character '\n' is read before the required byte size is read, it will return early.


Notes on fgets() function 1

fgets()The maximum read size of the function is its " 第二个参数减1". This is because the string is regarded ’\0’as terminator. fgets()In order to ensure the input content 字符串格式, when the input data size exceeds 第二个参数the specified size, fgets()only the previous " 第二个参数减1" will be read. characters, and 1个字符space is reserved to store the string terminator ’\0’.

Test code:

#include <stdio.h>
int main(void)
{
    
    
	char a[10] = {
    
    0};
	printf("你的输入:");
	fgets(a, 4, stdin);
	//printf("%s\n", a);//下面这句的输出和这句是一样的
	printf("printf(\"%%s\\n\", a)%c==>%s\n", ';', a);
	return 0;
}

running result:

Insert image description here

In this example, fgets()the second parameter is 4, so it can only store at most (4-1 = 3)characters entered into the address space pointed to by the first parameter. Enter " abcde", there is only " abc" in the array a[].


Notes on fgets() function 2

In fgets()the eyes of the function, the newline character ’\n’is just the one it wants to read 普通字符. When reading keyboard input, the last entered carriage return character will also be stored in the array.That is to say, '\n' will also be stored in the array., and because the string itself will ’\0’end with. Therefore, before the number of input characters exceeds 第二个参数指定大小, if you enter na character and press Enter, the number of bytes fgets()stored in the memory address specified by the first parameter will be n+2the same. There will be one more ’\n’and one at the end ’\0’, and the one ’\n’in ’\0’front of ( \n\0).

Test code:

#include <stdio.h>
int main(void)
{
    
    
	char a[10] = {
    
    0};
	printf("你的输入:");
	fgets(a, 10, stdin);
	//printf("%s\n", a);//下面这句的输出和这句是一样的
	printf("printf(\"%%s\\n\", a)%c==>%s\n", ';', a);
	for(int i=0; i<10; i++)
	{
    
    
		if(a[i] == '\n')
			printf("a[%d]是换行符'\\n'\n", i);
		if(a[i] == '\0')
			printf("a[%d]是字符串结束符'\\0'\n", i);
	}
	return 0;
}

running result:

Insert image description here
In this example, since the input characters are smaller than 参数2the specified ones 最大读取字符数, fgets()the function will ’\n’also store the newline characters a[]in the array. In the third line of the running interface 换了两次行,It is the result of the combination of the extra newline character '\n' and the newline character '\n' in my output code.


Notes on fgets() function 3

fgets()The function is only responsible 读取and will not clear 参数1the pointed address memory in advance. The bytes read will beOverwrite original address storage, but the content not covered is stillstay as is

Test code:

#include <stdio.h>
int main(void)
{
    
    
	char a[10] = {
    
    '1','1','1','1','1','1','1','1','1','1'};
	printf("你的输入:");
	fgets(a, 10, stdin);
	//printf("%s\n", a);//下面这句的输出和这句是一样的
	printf("printf(\"%%s\\n\", a)%c==>%s\n", ';', a);
	for(int i=0; i<10; i++)
	{
    
    
		if(a[i] == '\n' || a[i] == '\0')
			printf("a[%d] = '\\%c'", i, a[i]=='\n'?'n':'0');
		else
			printf("a[%d] = %c", i, a[i]);
		printf("\n");
	}
	return 0;
}

operation result:

Insert image description here


Notes on fgets() function 4

When using fgets()a function to read keyboard input, if you enter 第二个参数减1data that is more than " " characters in size, fgets()only the first " 第二个参数减1" characters will be read.Extra characters remain in the input buffer. If it is not cleared, it may affect the next input.

Test code:

#include <stdio.h>
int main(void)
{
    
    
	char a[4] = {
    
    0};
	char b[10] = {
    
    0};
	printf("存进a的输入:");
	fgets(a, 4, stdin);
	for(int i=0; i<4; i++)
		printf("a[%d] = %c\n", i, a[i]);
	printf("存进b的输入:");
	fgets(b, 10, stdin);
	printf("这里没有阻塞等待输入,而是直接跳过了\n");
	//printf("%s", a);//下面这句的输出和这句是一样的
	printf("printf(\"%%s\", b)%c==>%s", ';', b);
	return 0;
}

operation result:

Insert image description here

In this example, abcdeafter entering " ", after a[]reading the array " abc",When the code runs to line 11, it does not stop and wait for user input., but it is read directly and remains incache areaThe " " inside is returned after de\nbeing read ‘\n’, so my last line of output code did not add a newline character ’\n’because the array b[]already contains a newline character ’\n’.


Notes on fgets() function 5

Will update when encountered. . .

Zero BUG is a matter of principle.

Guess you like

Origin blog.csdn.net/L_0x0b/article/details/86684918