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.
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)
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.
#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);}