Fgets

From TORI
Jump to navigation Jump to search

fgets is element of C++ language.

fgets is used to read the file until the end of the current line.

Use:

fgets(куда, \( n \), откуда);

fgets needs 3 arguments:

1. куда: name of string, where to place the input. In the simplest case, it is a character array.

2. \( n \): number of characters to read. In a simplest case, an integer constant. If the string at the input is longer, only \( n \) characters will be red.

3. откуда: address, from where to read. For example, some variable, declared as FILE *

fgets helps to treat the human-oriented files, while the creators did not care about length of the line, nor about place, where the data are placed. The line can be read with fgets and then treated with other commands, dividing it to sentences and/or searching for some keywords or numbers there.

Example

#include<stdio.h>
int main()
{
char s[99];
FILE * i;
i=fopen("0.txt","r");
fgets(s,99,i);
close(i);
print("%s",s);
}

More complicated example

https://www.educative.io/edpresso/how-to-use-the-fgets-function-in-c

int main(){
char str[20];
fgets(str, 20, stdin); // read from stdin
puts(str); // print read content out to stdout
// open the file
FILE *f = fopen("file.txt" , "r"); 
// if there was an error
if(f == NULL){
perror("Error opening file"); // print error
return(-1); 
}
// if there was no error
else{ 
fgets(str, 20, f); // read from file
puts(str); // print read content out to stdout
}
fclose(f); // close file
return(0);
}

Warning

Only few elements of C++ (used to generate pictures and tables) are described in TORI.

References

https://solarianprogrammer.com/2019/04/03/c-programming-read-file-lines-fgets-getline-implement-portable-getline/

Keywords

C++, FILE, fclose, fopen, input