[英]C - Terminal Write and Output to a Text File
我是一名参加 C 入门课程的学生,我们的第一个 C 期中考试即将到来。 我们的测试环境会将我们的操作和 printf 输出存储到一个文本文件中。 just in-case.但是,我们的助教建议我们自己使用写入文件以防万一。
) to a text file like output.txt?有没有一种非常简单的方法可以将我的终端/控制台输出和输入(我在之后输入的内容)复制到像 output.txt 这样的文本文件中?
我试过
freopen("output.txt","w",stdout);
但这不会将我的 scanf 输入写入文本文件。
任何人都可以帮忙吗?
不要使用 scanf(); 使用 fgets(); 一个例子:
#include <stdio.h>
#include <stdlib.h>
#define Contents_Size 1000
int main()
{
char contents[Contents_Size];
//Opening the file
FILE * fp;
fp = fopen("\myfile.txt", "w"); //"w" = write
//If there is an error
if(fp == NULL)
{
//Exit
printf("Error!\n");
exit(EXIT_FAILURE);
}
//This part require your input
printf("Enter the contents of file: \n");
fgets(contents, Contents_Size, stdin);
//Write your input in file
fputs(contents, fp);
//Close the file
fclose(fp);
return 0;
}
fgest() 将复制您在内容 [] 中的输入,而 fputs() 会将内容 [] 的每个字符粘贴到您的文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.