Lowercase characters to Uppercase characters in C

2019-03-07 05:55发布

问题:

I am reading content from a file to be read into a char array in C. How could I change all the letters in the file that are lowercase to uppercase letters?

回答1:

Here's a possible algorithm:

  1. Open a file (let's call it A) - fopen()
  2. Open another file to write (let's call it B) - fopen()
  3. Read the content of A - getc() or fread(); whatever you feel free
  4. Make the content you read uppercase - toupper()
  5. Write the result of the 4-step to B - fwrite() or fputc() or fprintf()
  6. Close all file handles - fclose()

The following is the code written in C:

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

#define INPUT_FILE      "input.txt"
#define OUTPUT_FILE     "output.txt"

int main()
{
    // 1. Open a file
    FILE *inputFile = fopen(INPUT_FILE, "rt");
    if (NULL == inputFile) {
        printf("ERROR: cannot open the file: %s\n", INPUT_FILE);
        return -1;
    }

    // 2. Open another file
    FILE *outputFile = fopen(OUTPUT_FILE, "wt");
    if (NULL == inputFile) {
        printf("ERROR: cannot open the file: %s\n", OUTPUT_FILE);
        return -1;
    }

    // 3. Read the content of the input file
    int c;
    while (EOF != (c = fgetc(inputFile))) {
        // 4 & 5. Capitalize and write it to the output file
        fputc(toupper(c), outputFile);
    }

    // 6. Close all file handles
    fclose(inputFile);
    fclose(outputFile);

    return 0;
}