C Program to Convert the Content of File to Lowercase

This C program takes the name of an input file as user input and converts its content to lowercase. The converted content is then saved in a new file called ‘output.txt’.

Problem Statement

Write a C program that reads the content of a file, converts it to lowercase, and saves the modified content in another file.

C Program to Convert the Content of File to Lowercase

#include <stdio.h>
#include <ctype.h>

#define MAX_SIZE 1000

int main() {
    FILE *inputFile, *outputFile;
    char fileName[100], ch;

    printf("Enter the name of the input file: ");
    scanf("%s", fileName);

    // Open the input file in read mode
    inputFile = fopen(fileName, "r");
    if (inputFile == NULL) {
        printf("Cannot open file '%s'\n", fileName);
        return 1;
    }

    // Open the output file in write mode
    outputFile = fopen("output.txt", "w");
    if (outputFile == NULL) {
        printf("Cannot create output file\n");
        return 1;
    }

    // Read characters from input file and convert to lowercase
    while ((ch = fgetc(inputFile)) != EOF) {
        fputc(tolower(ch), outputFile);
    }

    printf("Content converted to lowercase and saved to 'output.txt'\n");

    // Close the files
    fclose(inputFile);
    fclose(outputFile);

    return 0;
}

How it works

  1. The program starts by asking the user to enter the name of the input file.
  2. It then attempts to open the input file in read mode using fopen(). If the file cannot be opened, an error message is displayed, and the program terminates.
  3. Next, it creates an output file called ‘output.txt’ using fopen() in write mode. If the output file cannot be created, an error message is displayed, and the program terminates.
  4. The program reads each character from the input file using fgetc() in a loop until it reaches the end of the file (EOF).
  5. Inside the loop, each character is converted to lowercase using tolower() function, and the lowercase character is written to the output file using fputc().
  6. After the loop finishes, the program displays a success message and closes both the input and output files using fclose().
  7. Finally, the program terminates with a return value of 0.

Input / Output

C Program to Convert the Content of File to Lowercase

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program finds the Greatest Common Divisor (GCD) of two given numbers. Problem Statement Write a C program that...
This C program calculates the roots of a quadratic equation of the form ax^2 + bx + c = 0....
This C program allows you to find the length of a linked list, which is the number of nodes present...