使用文件进行读取或输出的两种方式(重定向版和fopen版)

1.重定向版

//利用文件进行读取和输出(重定向版)
//如果想要标准输入而文件输出时,只需将关于文件输入的语句注释掉即可,文件输入标准输出同理
//如果想回到标准输入输出时,只需将下一行的本地定义注释掉即可
#define LOCAL
#include<iostream>
#include<cstdio>
#include<fstream>
using namespace std;
int main()
{
    #ifdef LOCAL
    freopen("input.txt","r",stdin);                 //scanf从文件中读取
    freopen("output.txt","w",stdout);               //printf到文件
    #endif // LOCAL
    int x,n=0,min=100,max=-100,s=0;
    while(scanf("%d",&x)==1)
    {
        s+=x;
        if(min>x) min=x;
        if(max<x) max=x;
        n++;
    }
    printf("%d %d %.3f\n",min,max,(double)s/n);
    return 0;
}

2.fopen版

//使用文件输入输出,但当禁止使用重定向的方式时,采用如下方法
//此时为文件读入,标准输出
#include<iostream>
#include<cstdio>
#include<fstream>
using namespace std;
int main()
{
    FILE *fin,*fout;
    fin=fopen("input.txt","rb");                //文件读取
    //fout=fopen("output.txt","wb");                  //输出到文件
    //fin=stdin;                                              //把fopen版的程序改成读写标准输入输出
    fout=stdout;
    int x,n=0,min=100,max=-100,s=0;
    while(fscanf(fin,"%d",&x)==1)                   //scanf变为fscanf
    {
        s+=x;
        if(min>x) min=x;
        if(max<x) max=x;
        n++;
    }
    fprintf(fout,"%d %d %.3f\n",min,max,(double)s/n);           //printf变为fprintf
    fclose(fin);                                                    //关闭两个文件
    fclose(fout);
    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 `std::process::Command` 将输出重定向文件中并读取,可以使用 `stdout` 方法来设置输出重定向文件,然后使用 `output` 方法执行命令并获取输出。 下面是一个示例,演示如何将命令的输出重定向文件中并读取: ```rust use std::process::{Command, Stdio}; use std::fs::File; use std::io::prelude::*; fn main() { // 创建一个文件用于保存命令的输出 let mut file = File::create("output.txt").expect("failed to create file"); // 创建 Command 并设置输出重定向文件 let output = Command::new("ls") .arg("-l") .stdout(Stdio::from(file)) .output() .expect("failed to execute process"); // 检查命令的执行状态 if output.status.success() { println!("Command executed successfully!"); } else { println!("Command failed!"); } // 读取保存在文件中的输出 let mut contents = String::new(); File::open("output.txt") .expect("failed to open file") .read_to_string(&mut contents) .expect("failed to read file"); println!("Output: {}", contents); } ``` 在上面的示例中,我们首先创建了一个名为 "output.txt" 的文件来保存命令的输出。然后,通过 `stdout` 方法将 `Command` 结构体的输出重定向到该文件。接着使用 `output()` 方法执行命令,并通过 `output.status` 来检查命令的执行状态。 最后,我们使用 `File::open()` 方法打开保存输出文件,并使用 `read_to_string()` 方法将文件内容读取到一个字符串中,然后将该字符串打印出来。 希望这可以帮助到你!如果你有更多关于 `std::process::Command` 的问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值