C 中的书面文本文件为空且不显示任何字符
Written text file in C is empty and does not show any characters
该程序应从读取任何键盘输入开始,然后一次将一个字符写入磁盘文件,称为 test.ext
要终止代码,您应该能够输入 EOF 序列(我相信 Windows 的 Crt^z)。
输入-键盘
输出 - test.txt(磁盘文件)
#include<stdio.h>
void main() {
FILE *ptr;
char ch;
ptr = fopen("test.txt", "w");
do {
ch = getchar();
putchar(ch);
} while (ch != EOF);
fclose(ptr);
}
您正在使用 putchar()
其中:
Writes a character to the standard output (stdout).
当您真的想写入 ptr
文件时。您可以像这样使用 fprintf()
写入文件:
fprintf(ptr, "%c", ch);
或者更好的是,您可以使用 fputc()
将单个字符写入文件:
fputc(ch, ptr);
你需要一个像 fputc()
这样的函数,它有一个额外的输出流参数,你可以选择输出应该指向的位置,而不是 putchar()
写入 stdout
仅:
int main(void)
{
FILE *ptr;
char ch;
ptr = fopen("test.txt", "w");
if (!ptr)
{
perror("test.txt");
return 1;
}
do {
ch = getchar();
fputc(ch, ptr); //note this line
} while (ch != EOF);
fclose(ptr);
return 0;
}
该程序应从读取任何键盘输入开始,然后一次将一个字符写入磁盘文件,称为 test.ext
要终止代码,您应该能够输入 EOF 序列(我相信 Windows 的 Crt^z)。
输入-键盘 输出 - test.txt(磁盘文件)
#include<stdio.h>
void main() {
FILE *ptr;
char ch;
ptr = fopen("test.txt", "w");
do {
ch = getchar();
putchar(ch);
} while (ch != EOF);
fclose(ptr);
}
您正在使用 putchar()
其中:
Writes a character to the standard output (stdout).
当您真的想写入 ptr
文件时。您可以像这样使用 fprintf()
写入文件:
fprintf(ptr, "%c", ch);
或者更好的是,您可以使用 fputc()
将单个字符写入文件:
fputc(ch, ptr);
你需要一个像 fputc()
这样的函数,它有一个额外的输出流参数,你可以选择输出应该指向的位置,而不是 putchar()
写入 stdout
仅:
int main(void)
{
FILE *ptr;
char ch;
ptr = fopen("test.txt", "w");
if (!ptr)
{
perror("test.txt");
return 1;
}
do {
ch = getchar();
fputc(ch, ptr); //note this line
} while (ch != EOF);
fclose(ptr);
return 0;
}