编辑:添加 #include <stdlib.h>,删除 static 描述 main()
我的建议,基于复制我大学给出的文件的示例。
我使用了 ctype.h 中的 toupper(),如果你不想使用它,你可以在与你的解决方案类似的条件下添加 32
注意:可能有char c 而不是int c。 (在原始版本中,它实际上是char;我更改了它,因为如果您查看处理c 的所有函数的文档中的标题,它们都采用/返回int,而不是char;在您的版本更重要,因为你保留一个数组,在我的程序中它几乎没有任何变化——int 只是我的首选做法)。
注2:我实际上从未深入研究过“w”/“r”(写入/读取)和“wb”/“rb”(写入/读取二进制)之间的区别。代码似乎可以正常工作。
(我认为当文件是文本文件时没有太大区别,为了进一步确保两个版本都能正常工作,请注意代码使用 feof() 来处理 EOF)
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void) {
FILE *from, *to;
int c;//could be char
/* opening the source file */
if ((from = fopen("text.txt", "rb")) == NULL) {
printf("no such source file\n");
exit(1);
}
/* opening the target file */
if ((to = fopen("program.txt", "wb")) == NULL) {
printf("error while opening target file\n");
exit(1);
}
while (!feof(from)) {
c = fgetc(from);
if (ferror(from)) {
printf("error while reading from the source file\n");
exit(1);
}
if (!feof(from)) {//we avoid writing EOF
fputc(toupper(c), to);
if (ferror(to)) {
printf("error while writing to the target file\n");
exit(1);
}
}
}
if (fclose(from) == EOF) {
printf("error while closing...\n");
exit(1);
}
if (fclose(to) == EOF) {
printf("error while closing...\n");
exit(1);
}
return 0;
}
对于从命令行获取参数的版本(也适用于 Windows)将 main 的开头替换为
int main(int argc, char *argv[]) {
FILE *from, *to;
char c;
/* checking the number of arguments in the command line */
if (argc != 3) {
printf("usage: name_of_executable_of_this_main <f1> <f2>\n");//name_of_exe could be copy_to_upper, for example; change adequately
exit(1);
}
/* opening the source file */
if ((from = fopen(argv[1], "rb")) == NULL) {
printf("no such source file\n");
exit(1);
}
/* opening the target file */
if ((to = fopen(argv[2], "wb")) == NULL) {
printf("error while opening the target file\n");
exit(1);
}