C fputs() and fgets()

Introduction to C fputs() and fgets()

In the C programming language, there are several functions available for reading and writing data from and to files. Two commonly used functions for file input/output operations are fputs() and fgets(). These functions provide a convenient way to handle text data in files.

Using C fputs() for Writing to Files

The fputs() function is used to write a string to a file. It takes two arguments: the string to be written and the file pointer. The file pointer is a variable that represents the file being written to. Here’s an example:


#include <stdio.h>

int main() {
   FILE *file;
   char str[] = "Hello, world!";

   file = fopen("example.txt", "w");
   if (file == NULL) {
      printf("Unable to open file.n");
      return 1;
   }

   fputs(str, file);
   fclose(file);

   return 0;
}

In this example, we first declare a file pointer variable named ‘file’. We then create a string ‘str’ containing the text we want to write to the file. Next, we use the fopen() function to open a file named ‘example.txt’ in write mode. If the file cannot be opened, an error message is displayed. If the file is successfully opened, we use fputs() to write the string to the file. Finally, we close the file using the fclose() function.

Using C fgets() for Reading from Files

The fgets() function is used to read a line of text from a file. It takes three arguments: a character array to store the read line, the maximum number of characters to read, and the file pointer. Here’s an example:


#include <stdio.h>

int main() {
   FILE *file;
   char str[100];

   file = fopen("example.txt", "r");
   if (file == NULL) {
      printf("Unable to open file.n");
      return 1;
   }

   fgets(str, 100, file);
   printf("Read from file: %s", str);
   fclose(file);

   return 0;
}

In this example, we declare a character array ‘str’ to store the read line from the file. We use the fopen() function to open the file named ‘example.txt’ in read mode. If the file cannot be opened, an error message is displayed. If the file is successfully opened, we use fgets() to read a line of text from the file and store it in the ‘str’ array. Finally, we print the read line using printf() and close the file using fclose().

The fputs() and fgets() functions are valuable tools for handling file input/output operations in the C programming language. With fputs(), you can easily write strings to a file, while fgets() allows you to read lines of text from a file. By understanding and utilizing these functions, you can efficiently work with text data in your C programs.

Scroll to Top