Detailed explanation of C/C++ fgets function


1. Introduction to fgets function

The fgets function reads a line from the specified stream and stores it in the string pointed to by str. It stops when (n-1) characters have been read, or when a newline character is read, or when the end of the file is reached, as the case may be.

2. fgets

1. fgets function header file

#include <stdio.h>

2. fgets function declaration

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

3. fgets function parameter and return value

str : This is a pointer to a character array that stores the string to be read.
n : This is the maximum number of characters to read (including the final null character). Usually the length of the array passed as str is used.
stream : This is a pointer to a FILE object that identifies the stream from which characters are to be read.
Return value : If successful, the function returns the same str parameter. If the end of the file is reached or no characters are read, the contents of str remain unchanged and a null pointer is returned. If an error occurs, returns a null pointer.
When end-of-file is encountered while reading characters, the eof indicator is set. If this situation is encountered before any characters have been read, the stream retains the original content and returns NULL; if a reading error occurs, the error indicator The device is set, returns NULL, and the value of the stream may be changed.

4. Usage examples

#include <stdio.h>
int main(int argc, char *argv[])
{
    
    
    FILE *fp = NULL;
	char buf[64] = {
    
    0};
	fp = fopen("./test.txt", "r");
	if (fp != NULL)
	{
    
    
		while (fgets(buf, sizeof(buf), fp))
		{
    
    
            printf("buf=%s\n", buf);
		}
		fclose(fp);
	}
    return 0;

The above code snippet will read the test.txt file and read each line of string through the fgets function.

5. Implementation of fgets function

char *fgets(char *s, int n,  FILE *stream)
{
    
    
   register int c;
   register char *cs;
   cs = s;

   while(--n > 0 && (c = getc(stream)) != EOF)
   {
    
    
      if((*cs++ =   c) == '\n')
      {
    
    
         break;
      }
   }

   *cs = '\0';
   return (c == EOF && cs == s) ? NULL : s ;
}

It can be seen from the source code that every time the fgets function is called, the formal parameter 1 will be assigned the read character, and finally assigned to '\0'.

3. Summary

Remember to use it with the sscanf function for better results.

Guess you like

Origin blog.csdn.net/weixin_37926485/article/details/130887323