0

I want to write the contents of the console to a text file. That's why first I wrote a program for this purpose, but the program just hung (didn't stop) and I couldn't even open the file to see the results.

The following is my code:

#include<stdio.h>

int main()
{
    // Print some lines on the output
    printf("Hello, world.\n");
    printf("My name\'s Amir Mohsen Ghasemi.\n");
    printf("I\'m 13 years old.\n");

    // Open a file in writing mode
    FILE *fp = fopen("Result.txt", "w");

    // Reset the file pointer of stdout to the beginning
    rewind(stdout);

    // Read a character from stdout and print it on fp
    while(!feof(stdout))
        putc(getc(stdout), fp);

    fclose(fp);
    return 0;
}

Then I searched on the web but most websites were talking about how to print contents of a file to the console. However, I found this question and then I used the freopen function like this:

#include<stdio.h>

int main()
{
    printf("Hello, world.\n");
    printf("My name\'s Amir Mohsen Ghasemi.\n");
    printf("I\'m 13 years old.\n");

    FILE *file = freopen("Result.txt", "r+", stdout);

    fclose(file);
    return 0;
}

but the program above couldn't give me what I expected and a file with 233.3 MB is generated and I wasn't even able to open it.

So, what's the problem and how can I exactly deal with it?

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • You can try the way as https://stackoverflow.com/questions/35185503/how-to-write-to-a-file-using-open-and-printf – caot May 02 '21 at 23:04

1 Answers1

1

To use r+ option in freopen() the file must be exist. to write or read data to new file use w+:

FILE* test = freopen("test.txt", "w+", stdout);
printf("hi from file");
fclose(test);
coderx64
  • 185
  • 1
  • 11