在C语言中,是否可以将标准输入/输出设置为文件?

4

标准输入/输出能否用于C程序的文件设置。我知道我们可以使用fscanf和fprintf从文件中读取和写入,但是否可以将标准i/o设置为文件,在C程序中仅使用printf / scanf进行i / o操作?

1个回答

7

在C语言中是否可以将标准输入/输出设置为文件?

是的,你可以使用 freopen 来实现。

以下是来自上述网站的示例代码:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    puts("stdout is printed to console");
    if (freopen("redir.txt", "w", stdout) == NULL)
    {
       perror("freopen() failed");
       return EXIT_FAILURE;
    }
    puts("stdout is redirected to a file"); // this is written to redir.txt
    fclose(stdout);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接