End and content of string received via fgets

Asked 1 years ago, Updated 1 years ago, 76 views

The fgets() function stores the results in the string and adds a null character (\0) to the end of the string. That's what IBM explains.

I'm going to compare the string I received through the fgets() function to the string I entered through the keyboard, and I'm going to compare it with the strcmp function, which is exactly the same output on the monitor, but instead of the zero result, it's different.

Actually, looking at the string I received through the fgets function, I could see that the end of the string I wanted was printed out as a tap, but I want to know why this phenomenon is happening.

    for(i = 0; i < 30; i++){
                    if((buffer[i] == '\t') || (buffer[i] == '\0') || (buffer[i] == ' ') || (buffer[i] == '\n')){
                        break;
                    }
                }

                if(strncmp(buffer, PW, i) == 0){
                    c = 0;
                }

Currently, we are comparing the length of the string through exception processing by collecting the cases where the margin may appear in the above way.

c string fileinputstream

2022-09-22 18:17

1 Answers

In C language, a string means a set of characters ending in '\0'.

fgets is a function that reads in line units from the specified file descriptor and fills in the buffer, but the raw data stored in the file does not contain the null character '\0', so it is added. If you don't have your own character, you won't know the length of the string you've been reading.

If there are multiple lines in the file, it is not visible in the plain text viewer, but there is an '\n' opening character at the end of each line.

Therefore, if you want to compare the string entered on the keyboard with the string imported into fgets, you can do the following.

// read to buffer with fgets

buffer[strlen(buffer)-1] = '\0'; // change the line character to null

if(strcmp(buffer, PW) == 0)
 c = 0;


2022-09-22 18:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.