C String Input and Output Functions
Syntax
char *fgets(char *str, int n, FILE *stream);
int fputs(const char *str, FILE *stream);
Example
#include <stdio.h>
int main () {
FILE *fp;
char str[60];
/* opening file for writing */
fp = fopen("file.txt" , "w");
printf("Enter a string: ");
fgets(str, 60, stdin);
/* writing content to the file */
fputs(str, fp);
/* closing the created file */
fclose(fp);
return 0;
}
Output
The output of the above example code will be a file named "file.txt" with the string entered by the user.
Explanation
The fgets()
and fputs()
functions are used for reading and writing strings respectively.
The fgets()
function reads up to n-1
characters from the stream stream
and stores them in the string str
. It stops reading either when it reads n-1
characters or a newline character (\n
) is read, whichever comes first. The string str
is terminated with a null character (\0
) after the last character read. If an error occurs, or the end of the file is reached before any characters are read, NULL
is returned.
The fputs()
function writes the string str
to the output stream stream
. If successful, it returns a non-negative value. If an error occurs, it returns EOF
.
Use
The fgets()
and fputs()
functions can be used for reading and writing strings to and from files in a C program. These functions are commonly used to handle text files or to accept user inputs in a console application.
Important Points
- It's important to check the return values of
fgets()
andfputs()
for error handling. - The
fgets()
function may read the newline character (\n
) that is added when the user presses enter. To remove this character from the string, it can be replaced with a null character (\0
) by usingstrtok()
or by manually changing the string. fgets()
is safer to use thangets()
as it allows the programmer to specify the maximum size to be read.
Summary
The C string input and output functions fgets()
and fputs()
provide a simple way to handle strings in file I/O or user inputs in console applications. Understanding the syntax and use of these functions can help prevent common programming errors and improve code readability.