Clear, practical technology insights About · Contact

Function Fgets ()() in C

Explore Function Fgets ()() in C with clear explanations, practical examples, and useful tips.

Published: 4 minutes read
Table of Contents

This guide covers function fgets ()() in c with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.

Declare Function Fgets ()() in C

Below is the declaration for fgets () in C:

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

Parameters

Str - This is the pointer to an array of char where the string to be read is stored.

n - This is the maximum number of characters to be read (including the last null character). Usually the length of the passed array is str used.

Stream - This is the pointer to a FILE object that identifies the Stream, where characters are read from.

Returns the value

If successful, the function returns the same parameter str. If EOF is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned.

If an error occurs, a null pointer is returned.

For example

The following program C illustrates the usage of the function fgets () in C:

 #include int main () { FILE * fp ; char str [ 60 ]; /* mo file de doc */ fp = fopen ( "baitapc.txt" , "r" ); if ( fp == NULL ) { perror ( "Xay ra loi trong khi doc file" ); return (- 1 ); } if ( fgets ( str , 60 , fp )!= NULL ) { /* Ghi noi dung len stdout */ puts ( str ); } fclose ( fp ); return ( 0 ); } 

Suppose we have baitapc. Txt with the following content. This file will be used as input for C program for example:

Compiling and running the above C program will result:

According to Tutorialspoint

Previous lesson: Function fgetc () in C

Next lesson: Function fputc () in C

Frequently Asked Questions

What should I check before following these steps?

Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.

Why might the process not work?

Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.

Can I undo the changes if necessary?

That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.

Was this article helpful?

Your feedback helps us improve.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.