C fputs()
and fgets()
Functions
Syntax
The syntax of the fputs()
function is:
int fputs(const char *str, FILE *stream);
The syntax of the fgets()
function is:
char *fgets(char *str, int n, FILE *stream);
Example
#include <stdio.h>
#include <stdlib.h>
#define MAX 256
int main() {
FILE *fp;
char str[MAX];
// Writing to a file using fputs()
fp = fopen("file.txt", "w");
fputs("Hello, World!", fp);
fclose(fp);
// Reading from a file using fgets()
fp = fopen("file.txt", "r");
if (fp == NULL) {
printf("File not found!");
exit(1);
}
fgets(str, MAX, fp);
printf("%s", str);
fclose(fp);
return 0;
}
Output
The output of the above example will be:
Hello, World!
Explanation
The fputs()
function is used to write a string to a file. It takes two parameters, a pointer to the string and a pointer to the file.
The fgets()
function is used to read a line of text from a file. It takes three parameters, a pointer to the string, the maximum number of characters to read, and a pointer to the file.
Both functions return values that indicate success or failure.
Use
The fputs()
and fgets()
functions are commonly used for reading and writing strings to and from files. They are useful for tasks such as creating and saving user data, storing configuration settings, and logging application events.
Important Points
- The
str
parameter infgets()
must be a character array and should have enough space to store the line being read. - When reading from a file, the
fgets()
function reads up to the specified number of characters or until it encounters a newline character. - When writing to a file, the
fputs()
function appends a null character ('\0'
) to the end of the string being written. - Both functions return a value of
NULL
if an error occurs while reading or writing to the file.
Summary
fputs()
and fgets()
are two important functions in the C programming language that are used for reading and writing strings to and from files. They provide a simple and efficient way to manage text-based data in files. Understanding these functions and their syntax can greatly enhance your ability to create robust file-handling code in your C programs.