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:
- Open a file (let's call it A) - fopen()
- Open another file to write (let's call it B) - fopen()
- Read the content of A - getc() or fread(); whatever you feel free
- Make the content you read uppercase - toupper()
- Write the result of the 4-step to B - fwrite() or fputc() or fprintf()
- 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;
}