C documentation V1 Help

Program: Converting Characters in a File to Uppercase

Problem Statement

Write a C program to read characters from a file, convert them to uppercase, and write the modified characters back to the file.

Algorithm

  1. Open File for Reading:

    • Use the fopen function to open the input file in read mode.

    FILE *inputFilePointer; inputFilePointer = fopen("input.txt", "r");
    • Check if the file is successfully opened.

    if (inputFilePointer == NULL) { // Handle file opening error }
  2. Open File for Writing:

    • Use the fopen function to open a temporary file in write mode.

    FILE *tempFilePointer; tempFilePointer = fopen("temp.txt", "w");
    • Check if the file is successfully opened.

    if (tempFilePointer == NULL) { // Handle file opening error }
  3. Read and Convert Characters:

    • Use a loop to read characters from the input file and convert them to uppercase.

    int character; while ((character = fgetc(inputFilePointer)) != EOF) { // Convert to uppercase character = toupper(character); // Write to the temporary file fputc(character, tempFilePointer); }
  4. Close Files:

    • Close both the input and temporary files.

    fclose(inputFilePointer); fclose(tempFilePointer);
  5. Remove Original File and Rename Temporary File:

    • Use the remove function to delete the original file.

    remove("input.txt");
    • Use the rename function to rename the temporary file to the original file name.

    rename("temp.txt", "input.txt");

Explanation

This program reads characters from the input file, converts them to uppercase using the toupper function, and writes the modified characters to a temporary file. After processing, it removes the original file and renames the temporary file to the original file name, effectively replacing the original file with the modified content.

Ensure that the input file exists and has the necessary permissions for reading and writing. This program provides a simple way to convert characters in a file to uppercase.

If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!

Last modified: 25 February 2024