C&中的小写字符为大写字符写入文件

时间:2015-01-18 03:55:55

标签: c character uppercase lowercase

我正在从一个文件中读取内容,以便在C中读取一个char数组。我怎样才能将文件中所有小写字母改为大写字母?

1 个答案:

答案 0 :(得分:1)

这是一种可能的算法:

  1. 打开一个文件(让我们称之为A) - fopen()
  2. 打开另一个要写的文件(让我们称之为B) - fopen()
  3. 阅读A - getc()或fread()的内容;无论你有什么自由
  4. 将您读取的内容设为大写 ​​- toupper()
  5. 将4步的结果写入B - fwrite()或fputc()或fprintf()
  6. 关闭所有文件句柄 - fclose()
  7. 以下是用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;
    }
    
相关问题