【问题标题】:Lowercase characters to Uppercase characters in C & writing to fileC中的小写字符到大写字符并写入文件
【发布时间】:2015-01-18 03:55:55
【问题描述】:

我正在从文件中读取内容以将其读入 C 中的 char 数组。如何将文件中所有小写字母更改为大写字母?

【问题讨论】:

  • ctype.htoupper
  • 到目前为止你在哪里?你取得了什么成就?例如,您可以复制文件内容吗?
  • 我已经能够解释这些字母并写入单独的文件,但我不确定如何覆盖文档。

标签: c character uppercase lowercase


【解决方案1】:

这是一个可能的算法:

  1. 打开一个文件(我们称之为A)-fopen()
  2. 打开另一个要写入的文件(我们称之为 B)- fopen()
  3. 读取A的内容——getc()或fread();随心所欲
  4. 将您阅读的内容设为大写 ​​- toupper()
  5. 将 4 步的结果写入 B - fwrite() 或 fputc() 或 fprintf()
  6. 关闭所有文件句柄 - fclose()

以下是用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;
}

【讨论】:

  • 良好的答案和良好的使用 int c 而不是 char c。然而,OP 并没有展示出太多值得这个好答案的工作。
  • 感谢您的评论!
  • 非常感谢!它奏效了,我能够很好地组织它,我很感激。
  • 我的荣幸!玩得开心!
猜你喜欢
  • 2020-03-01
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 2011-04-03
  • 2011-01-16
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
相关资源
最近更新 更多