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

Adi*_*idu 3 c file-io

可以将标准输入/输出设置为C程序的文件.我知道我们可以使用fscanf和fprintf来读取和写入文件但是通过将std i/o设置为文件,我们可以在C程序中使用printf/scanf进行i/o操作吗?

R S*_*ahu 6

是否可以将标准输入/输出设置为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);
}
Run Code Online (Sandbox Code Playgroud)