文件读写语句
  • 板块学术版
  • 楼主hjsxhst2022
  • 当前回复20
  • 已保存回复20
  • 发布时间2022/8/2 17:17
  • 上次更新2023/10/27 17:20:32
查看原帖
文件读写语句
745903
hjsxhst2022楼主2022/8/2 17:17

freopen是被包含于C标准库头文件<stdio.h>中的一个函数,用于重定向输入输出流。该函数可以在不改变代码原貌的情况下改变输入输出环境,但使用时应当保证流是可靠的,否则RE。

形参说明:

filename:需要重定向到的文件名或文件路径。

mode:代表文件访问权限的字符串。例如,"r"表示“只读访问”、"w"表示“只写访问”、"a"表示“追加写入”。

stream:需要被重定向的文件流。

返回值:如果成功,则返回该指向该输出流的文件指针,否则返回为NULL。

程序例

举例1

#include<stdio.h>
int main()
{
    /* redirect standard output to a file */
    if(freopen("D:\\output.txt", "w", stdout) == NULL)
        fprintf(stderr,"error redirecting stdout\n");
    /* this output will go to a file */
    printf("This will go into a file.\n");
    /*close the standard output stream*/
    fclose(stdout);
    return 0;
}

举例2

如果上面的例子您没看懂这个函数的用法的话,请看这个例子。

这个例子实现了从stdout到一个文本文件的重定向。即,把输出到屏幕的文本输出到一个文本文件中。

#include<stdio.h>
int main()
{
    int i;
    if (freopen ("D:\\output.txt", "w", stdout) == NULL)
        fprintf(stderr, "error redirecting stdout\n");
    for (i = 0; i < 10; i++)
        printf("%3d", i);
    printf("\n");
    fclose(stdout);
    return 0;
}

编译运行一下,你会发现,十个数输出到了D盘根目录下文本文件output.txt中。

举例3

从文件in.txt中读入数据,计算加和输出到out.txt中

#include<stdio.h>
int main()
{
    int a, b;
    freopen("in.txt","r",stdin);
    // 如果in.txt不在连接后的exe的目录,需要指定路径如D:\in.txt */
    freopen("out.txt","w",stdout); /*同上*/
    while (scanf("%d%d", &a, &b) != EOF)
        printf("%d\n",a+b);
    fclose(stdin);
    fclose(stdout);
    return 0;
}

恢复文件流

当标准输出stdout被重定向到指定文件后,如何把它重定向回原来“默认”的输出设备(即显示器)呢?

C标准库的回复是:不支持。没有任何方法可以恢复原来的输出流。

那是否存在依赖具体平台的实现呢?存在。

在操作系统中,命令行控制台(即键盘或者显示器)被视为一个文件,既然是文件,那么就有“文件名”。由于历史原因,命令行控制台文件在DOS操作系统和Windows操作系统中的文件名为"CON",在其它的操作系统(例如Unix、Linux、Mac OS X、Android等等)中的文件名为"/dev/tty"。

因此,在Windows中可以使用

freopen( "CON", "w", stdout );

其它操作系统中使用:

freopen( "/dev/tty", "w", stdout );

Windows代码举例

#include<stdio.h>
#include<stdlib.h>
int main()
{
    FILE *stream;
    if ((stream = freopen("file.txt", "w", stdout)) == NULL)
        exit(-1);
    printf("this is stdout output\n");
    stream = freopen("CON","w",stdout);
    /*stdout是向程序的末尾的控制台重定向*/
    printf("And now back to the console once again\n");
    return 0;
}

Linux代码举例

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    FILE *stream;
    if ((stream = freopen("file.txt", "w", stdout)) == NULL)
        exit(-1);
    printf("this is stdout output\n");
    stream = freopen("/dev/tty","w",stdout);
    /*stdout是向程序的末尾的控制台重定向*/
    printf("And now back to the console once again\n");
    return 0;
}

警告:在使用上述方法在输入输出流间进行反复的重定向时,极有可能导致流指针得到不被期待的结果,使输入输出发生异常,所以如果需要在文件的输入输出和标准输入输出流之间进行切换,建议使用fopen或者是C++标准的ifstream及ofstream。

最后的语句:

freopen("文件名.in","r",stdin);
freopen("文件名.out","w",stdout);

资料来源

本人并不保证以上代码是否可编译

2022/8/2 17:17
加载中...