简体   繁体   English

C - 终端写入和输出到文本文件

[英]C - Terminal Write and Output to a Text File

I am a student taking an introductory C course and have our first C midterm coming up.我是一名参加 C 入门课程的学生,我们的第一个 C 期中考试即将到来。 Our test environment would store our actions and printf output to a text file.我们的测试环境会将我们的操作和 printf 输出存储到一个文本文件中。 However, our TA suggested we write to a file ourselves using fprintf just in-case.但是,我们的助教建议我们自己使用fprintf写入文件以防万一。

Is there a very simple way I can copy my terminal/console output and input (what I enter in after scanf ) to a text file like output.txt?有没有一种非常简单的方法可以将我的终端/控制台输出和输入(我在scanf之后输入的内容)复制到像 output.txt 这样的文本文件中?

I tried我试过

freopen("output.txt","w",stdout); freopen("output.txt","w",stdout);

but that won't write my scanf input to the text file.但这不会将我的 scanf 输入写入文本文件。

Can anyone help?任何人都可以帮忙吗?

Don't use scanf();不要使用 scanf(); Use fgets();使用 fgets(); An example:一个例子:

#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() will copy your input in contents[] and fputs() will paste every char of contents[] in your file. fgest() 将复制您在内容 [] 中的输入,而 fputs() 会将内容 [] 的每个字符粘贴到您的文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM