C Programming Language Tutorial

Variables and Data Types

Input/Output

Looping and Selection Structures

Array

Functions

Preprocessing Command

Pointer

Structure

File Operations

Important Knowledge

Read And Write Files as Strings (fgets() And fputs() Functions) in C Programming Language

In this tutorial, we'll explore the fgets() and fputs() functions in the C programming language, which are used to read and write strings to and from a file. We'll cover the basic syntax, usage, and provide some examples to demonstrate their functions.

Basic Syntax

Before using fgets() and fputs(), you should include the stdio.h header at the beginning of your C program.

#include <stdio.h>

The basic syntax for fgets() and fputs() is as follows:

char *fgets(char *str, int n, FILE *stream);
int fputs(const char *str, FILE *stream);
  • fgets(): This function reads a string of at most n-1 characters from the given stream and stores it in the character array str. It stops reading if it encounters a newline character, end-of-file, or an error. The function returns str if successful, and NULL if an error occurs or end-of-file is reached.
  • fputs(): This function writes the null-terminated string str to the given stream. If the operation is successful, it returns a non-negative integer. Otherwise, it returns EOF.

Opening and Closing Files

Before using fgets() and fputs(), you need to open the file with fopen() and close it with fclose() when you're done.

The syntax for fopen() and fclose() is:

FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *stream);
  • filename: The name of the file to be opened.
  • mode: The mode in which the file is opened, such as "r" for reading, "w" for writing, and "a" for appending.
  • stream: The file pointer to the open file.

Basic Usage

Let's start with a simple example of reading a line from a file:

#include <stdio.h>

int main() {
    FILE *file = fopen("input.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    char line[256];
    if (fgets(line, sizeof(line), file) != NULL) {
        printf("Read line: %s", line);
    }

    fclose(file);
    return 0;
}

In this example, we open the file input.txt for reading, read a line using fgets(), and then close the file.

Next, let's write a string to a file:

#include <stdio.h>

int main() {
    FILE *file = fopen("output.txt", "w");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    const char *str = "Hello, world!\n";
    if (fputs(str, file) != EOF) {
        printf("Wrote string: %s", str);
    }

    fclose(file);
    return 0;
}

In this example, we open the file output.txt for writing, write the string "Hello, world!\n" using fputs(), and then close the file.

  1. Reading strings from a file with fgets() in C:

    • Description: fgets() is used to read strings (lines) from a file. It reads until a newline character or the specified limit.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("input.txt", "r");
          if (file != NULL) {
              char buffer[100];
      
              // Read a line from the file
              while (fgets(buffer, sizeof(buffer), file) != NULL) {
                  printf("Line from file: %s", buffer);
              }
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  2. Writing strings to a file using fputs() in C language:

    • Description: fputs() is used to write strings to a file. It appends a null-terminated string to the file.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("output.txt", "w");
          if (file != NULL) {
              const char *text = "Hello, File I/O!\n";
      
              // Write a string to the file
              fputs(text, file);
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  3. String-based file I/O in C programming:

    • Description: Use fgets() and fputs() for string-based file I/O, reading and writing lines of text.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *source = fopen("source.txt", "r");
          FILE *destination = fopen("destination.txt", "w");
      
          if (source != NULL && destination != NULL) {
              char buffer[100];
      
              // Read a line from source and write to destination
              while (fgets(buffer, sizeof(buffer), source) != NULL) {
                  fputs(buffer, destination);
              }
      
              fclose(source);
              fclose(destination);
          } else {
              printf("Error opening files.\n");
          }
      
          return 0;
      }
      
  4. Handling newline characters and buffer management with fgets():

    • Description: Handle newline characters read by fgets() and manage the buffer size accordingly.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("example.txt", "r");
          if (file != NULL) {
              char buffer[100];
      
              // Read a line from the file
              while (fgets(buffer, sizeof(buffer), file) != NULL) {
                  // Remove the newline character if present
                  if (buffer[strlen(buffer) - 1] == '\n') {
                      buffer[strlen(buffer) - 1] = '\0';
                  }
                  printf("Line from file: %s\n", buffer);
              }
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  5. Sequential file processing with fgets() and fputs() in C:

    • Description: Combine fgets() and fputs() for sequential processing of string-based file I/O.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *source = fopen("source.txt", "r");
          FILE *destination = fopen("destination.txt", "w");
      
          if (source != NULL && destination != NULL) {
              char buffer[100];
      
              // Read a line from source and write to destination
              while (fgets(buffer, sizeof(buffer), source) != NULL) {
                  fputs(buffer, destination);
              }
      
              fclose(source);
              fclose(destination);
          } else {
              printf("Error opening files.\n");
          }
      
          return 0;
      }
      
  6. C code examples demonstrating fgets() and fputs() usage:

    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *source = fopen("source.txt", "r");
          FILE *destination = fopen("destination.txt", "w");
      
          if (source != NULL && destination != NULL) {
              char buffer[100];
      
              // Read a line from source and write to destination
              while (fgets(buffer, sizeof(buffer), source) != NULL) {
                  fputs(buffer, destination);
              }
      
              fclose(source);
              fclose(destination);
          } else {
              printf("Error opening files.\n");
          }
      
          return 0;
      }
      
  7. Efficient buffering techniques for string-based file I/O in C:

    • Description: Use buffering to enhance performance when reading or writing strings to a file.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("buffered.txt", "w");
          if (file != NULL) {
              char buffer[BUFSIZ];
      
              // Set a custom buffer for the file
              setbuf(file, buffer);
      
              // Write to the file with the custom buffer
              fputs("Hello, Buffered IO!", file);
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }
      
  8. Random access file operations with fgets() and fputs() in C:

    • Description: Use fseek() to set the file position and then use fgets() or fputs() for random access with strings.
    • Code:
      #include <stdio.h>
      
      int main() {
          FILE *file = fopen("random_access.txt", "r+");
          if (file != NULL) {
              char buffer[100];
      
              // Set file position to the 5th line
              fseek(file, 4 * sizeof(buffer), SEEK_SET);
      
              // Read a line from the 5th position
              fgets(buffer, sizeof(buffer), file);
              printf("Line at position 5: %s", buffer);
      
              // Set file position to the end
              fseek(file, 0, SEEK_END);
      
              // Write a line at the end of the file
              fputs("New Line at the End", file);
      
              fclose(file);
          } else {
              printf("Error opening the file.\n");
          }
      
          return 0;
      }