0
votes

I am a student taking an introductory C course and have our first C midterm coming up. Our test environment would store our actions and printf output to a text file. However, our TA suggested we write to a file ourselves using fprintf just in-case.

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?

I tried

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

but that won't write my scanf input to the text file.

Can anyone help?

1
what about pFile = fopen ("output.txt","w");, and then do your fprintf?bruceg
Welcome to stackoverflow, please provide a minimal reproducible example. Because your question is not clear.Stargateur
@bruceg I would use pFile = fopen("output.txt","w") but having to do both printf and fprintf during my midterm would be long and kinda messy. I was asking if there is a one line solution like freopen("output.txt","w",stdout); ,but the problem with that code is that it doesn't write my scanf inputs. I basically just want a code that copies the terminal into a text file.Simmon Thind

1 Answers

0
votes

Don't use scanf(); Use 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.