博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
标准输入输出重定向
阅读量:6078 次
发布时间:2019-06-20

本文共 2116 字,大约阅读时间需要 7 分钟。

转自:

 

1. C:

#include <stdio.h>

#include <stdlib.h>

void test_stdin()

{

    char buf[128];

freopen("1.txt", "r", stdin); //redirect stdin

    scanf("%s",buf);

    printf("%s\n",buf);

    freopen("CON", "r", stdin); //recover(Windows)

//freopen("/dev/console", "r", stdin); //recover(Linux)

//freopen("/dev/pts/0", "r", stdin); //recover stdin(Linux : my putty client)

    scanf("%s",buf);

    printf("%s\n",buf);

}

void test_stdout()

{

    freopen("1.txt", "w", stdout); //redirect stdout

    printf("test");

    freopen("CON", "w", stdout); //recover stdout(Windows)

//freopen("/dev/console", "w", stdout); //recover stdout(Linux)

//freopen("/dev/pts/0", "w", stdout); //recover stdout(Linux : my putty client)

    printf("OK\n");

}

int main()

{

    printf("Test stdout : \n");

    test_stdout();

    printf("Test stdin : \n");

    test_stdin();

    return 0;

}

 

2.Python:

#! /usr/bin/python

import sys

'''

  File : redirect.py

  Author : Mike

  E-Mail : Mike_Zhang@live.com

'''

print "Test stdout : "

#redirect stdout

tmp = sys.stdout

fp = open("1.txt","w")

sys.stdout = fp

print 'Just a test'

sys.stdout = tmp #recover stdout

print 'test2'

fp.close()

print "Test stdin : "

#redirect stdin

tmp = sys.stdin

fp = open("1.txt","r")

sys.stdin = fp

strTest = raw_input()

print strTest

sys.stdin = tmp # recover stdin

strTest = raw_input()

print strTest

fp.close()

 

3. C++:

#include <iostream>

#include <fstream>

void main()

{

    std::ofstream logFile("c://out.txt");

    std::streambuf *outbuf = std::cout.rdbuf(logFile.rdbuf());

    std::streambuf *errbuf = std::cerr.rdbuf(logFile.rdbuf());

    // do the actual work of the program;

    // GUI code and event loop would go here

    std::cout << "This would normally go to cout but goes to the log file/n";

    std::cerr << "This would normally go to cerr but goes to the log file /n";

    logFile << "This goes to the log file/n";

    // end of program body

    // restore the buffers

    std::cout.rdbuf(outbuf);

    std::cerr.rdbuf(errbuf);

    // It will output in your console

    std::cout << "This would normally go to cout but goes to the log file/n";

    std::cerr << "This would normally go to cerr but goes to the log file /n";

}

转载于:https://www.cnblogs.com/qinfengxiaoyue/p/4059592.html

你可能感兴趣的文章
VMWare虚拟机系统网络配置
查看>>
性能优化你必须知道的那些事儿
查看>>
锋利的jQuery-4--给事件添加命名空间
查看>>
linux概念之cpu分析
查看>>
性能调优攻略
查看>>
Java策略模式(Strategy模式) 之体验
查看>>
负载均衡探测器lbd
查看>>
【转】浅谈.net remoting 与webservice
查看>>
Golang 笔记 5 go语句
查看>>
ef core
查看>>
JavaScript——DOM或以树形展示的Web页面
查看>>
Linux之用户管理--初级上
查看>>
使用Chrome快速实现数据的抓取(一)——概述
查看>>
数据库原理及应用第7章课后习题答案
查看>>
开始前的准备
查看>>
LeetCode(30) Substring with Concatenation of All Words
查看>>
互联网广告思维导图,各种名称解释看这篇就够了
查看>>
SQL索引一步到位
查看>>
Java中toArray的用法探究(java数组与list转换)
查看>>
Linux服务器沦陷为肉鸡的全过程实录
查看>>