fgets() in C

File reading can be tricky for an amateur programmer; however, C++ has made it easier with the fgets() function that allows files to be read.

Syntax

fgets() takes three parameters that are defined when the function is called. The following code explains how the function is declared:

char *fgets(char *string, int size, FILE *filePointer)

Parameters

  • string: the target character array where the file data is read and stored.
  • size: the amount of characters we want to read in the file.
  • filePointer: points to the file being read.

Code

The following code reads a file named "file.txt" up to 10 characters and stores it in string s. file.txt has a string of i love educative and programming, but string s only reads the first 10 characters.

main.c
file.txt
#include <stdio.h>
int main()
{
int size = 10;
char s [size];
FILE * filePointer;
filePointer = fopen("file.txt" , "r");
fgets(s, size, filePointer);
printf("string is: %s\n", s);
}
Copyright ©2024 Educative, Inc. All rights reserved