Lowercase characters to Uppercase characters in C & writing to file

青春壹個敷衍的年華 提交于 2019-12-02 23:39:19

问题


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;
}


来源:https://stackoverflow.com/questions/28006976/lowercase-characters-to-uppercase-characters-in-c-writing-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!