【问题标题】:How can I write contents shown on the output to file?如何将输出中显示的内容写入文件?
【发布时间】:2021-07-25 10:35:58
【问题描述】:

我想将控制台的内容写入文本文件。这就是为什么我首先为此目的编写了一个程序,但程序只是挂起(没有停止),我什至无法打开文件查看结果。

以下是我的代码:

#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;
}

然后我在网上搜索,但大多数网站都在讨论如何将文件的内容打印到控制台。但是,我找到了this question,然后我像这样使用了freopen 函数:

#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;
}

但上面的程序无法满足我的预期,并且生成了一个 233.3 MB 的文件,我什至无法打开它。

那么,问题出在哪里,我该如何解决呢?

【问题讨论】:

标签: c file printf stdout


【解决方案1】:

要在 freopen() 中使用 r+ 选项,文件必须存在。向新文件写入或读取数据使用 w+:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多