Lowercase characters to Uppercase characters in C & writing to file

后端 未结 1 1136
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-29 14:56

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条回答
  • 2021-01-29 15:25

    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;
    }
    
    0 讨论(0)
提交回复
热议问题