cin 및 cout을 파일로 리디렉션하는 방법은 무엇입니까?


답변:


219

수행하려는 작업의 실제 예는 다음과 같습니다. 주석을 읽고 코드의 각 줄이 무엇을하는지 알 수 있습니다. gcc 4.6.1로 내 PC에서 테스트했습니다. 잘 작동합니다.

#include <iostream>
#include <fstream>
#include <string>

void f()
{
    std::string line;
    while(std::getline(std::cin, line))  //input from the file in.txt
    {
        std::cout << line << "\n";   //output to the file out.txt
    }
}
int main()
{
    std::ifstream in("in.txt");
    std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf
    std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!

    std::ofstream out("out.txt");
    std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
    std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!

    std::string word;
    std::cin >> word;           //input from the file in.txt
    std::cout << word << "  ";  //output to the file out.txt

    f(); //call function


    std::cin.rdbuf(cinbuf);   //reset to standard input again
    std::cout.rdbuf(coutbuf); //reset to standard output again

    std::cin >> word;   //input from the standard input
    std::cout << word;  //output to the standard input
}

다음 과 같이 한 줄로 저장 하고 리디렉션 할 수 있습니다.

auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save and redirect

여기서 버퍼를로 std::cin.rdbuf(in.rdbuf())설정 한 다음에 연결된 이전 버퍼를 반환합니다 . 또는 그 문제에 대한 모든 스트림 에서도 마찬가지 입니다.std::cin'sin.rdbuf()std::cinstd::cout

희망이 도움이됩니다.


4
cin 및 cout을 표준 IO로 재설정하기 전에 파일을 닫아야합니까?
updogliu

3
@updogliu : 아니요 당신이 원하는 경우에, 당신이 사용할 수있는 inout에서 쓸 수 읽기, in.txt그리고 out.txt각각. 또한, 파일이 때 자동으로 종료됩니다 inout범위 밖으로 이동합니다.
Nawaz

내가 사용하면 freopen더 이상 stdout돌아올 수 없기 때문에이 솔루션을 선호합니다 freopen. stackoverflow.com/questions/26699524/…
xxks-kkk

88

그냥 써

#include <cstdio>
#include <iostream>
using namespace std;

int main()
{
    freopen("output.txt","w",stdout);
    cout<<"write in file";
    return 0;
}

14
그게 stdout아니라 리디렉션 중 cout입니다.
updogliu

5
이것은 printf도 리다이렉트 할 것이고, 어떤 경우에는 좋을 수도 있습니다.
JDiMatteo

5
@AkshayLAradhya std::sync_with_studio(false);기본 설정은로 설정되어 있지만 설정하지 않은 경우 true.
vsoftco

2
@ PřemyslŠťastný 왜?
reggaeguitar

4
답변이 기능면에서 동일하다면 C ++에 해당하는 것은 ofstream out("out.txt"); cout.rdbuf(out.rdbuf());한 줄만 추가 가능하며 이식 가능합니다. 너무 간단하지 않습니다 :)
nevelis

19

다음은 콘테스트 프로그래밍에 유용한 cin / cout 섀도 잉을위한 짧은 코드 스 니펫입니다.

#include <bits/stdc++.h>

using namespace std;

int main() {
    ifstream cin("input.txt");
    ofstream cout("output.txt");

    int a, b;   
    cin >> a >> b;
    cout << a + b << endl;
}

이는 일반 fstream이 동기화 된 stdio 스트림보다 빠르다는 추가 이점을 제공합니다. 그러나 이것은 단일 기능의 범위에서만 작동합니다.

글로벌 cin / cout 리디렉션은 다음과 같이 쓸 수 있습니다 :

#include <bits/stdc++.h>

using namespace std;

void func() {
    int a, b;
    std::cin >> a >> b;
    std::cout << a + b << endl;
}

int main() {
    ifstream cin("input.txt");
    ofstream cout("output.txt");

    // optional performance optimizations    
    ios_base::sync_with_stdio(false);
    std::cin.tie(0);

    std::cin.rdbuf(cin.rdbuf());
    std::cout.rdbuf(cout.rdbuf());

    func();
}

참고 ios_base::sync_with_stdio또한 재설정std::cin.rdbuf . 따라서 순서가 중요합니다.

ios_base :: sync_with_stdio (false)의 의미 도 참조하십시오 . cin.tie (NULL);

std io 스트림은 단일 파일의 범위에 대해 쉽게 음영 처리 될 수 있으므로 경쟁적인 프로그래밍에 유용합니다.

#include <bits/stdc++.h>

using std::endl;

std::ifstream cin("input.txt");
std::ofstream cout("output.txt");

int a, b;

void read() {
    cin >> a >> b;
}

void write() {
    cout << a + b << endl;
}

int main() {
    read();
    write();
}

그러나이 경우 std선언을 하나씩 선택 using namespace std;하고 모호한 오류가 발생할 수 있으므로 피해야 합니다.

error: reference to 'cin' is ambiguous
     cin >> a >> b;
     ^
note: candidates are: 
std::ifstream cin
    ifstream cin("input.txt");
             ^
    In file test.cpp
std::istream std::cin
    extern istream cin;  /// Linked to standard input
                   ^

C ++에서 네임 스페이스를 올바르게 사용하는 방법 도 참조하십시오 . , 왜 "네임 스페이스를 사용하여 STD"입니다 나쁜 관행으로 간주? 그리고 어떻게 C ++ 네임 스페이스와 전역 함수 사이에 이름 충돌을 해결하기 위해?


15

컴파일 프로그램 이름이 x.exe이고 $가 시스템 쉘 또는 프롬프트라고 가정

$ x <infile >outfile 

infile에서 입력을 받아 outfile로 출력합니다.


그것은 C ++과 관련이 없으며 사소한 예제에서 실패합니다 (예 : 프로그램이 콘솔에 쓰는 하위 프로세스를 생성하는 경우). 적어도 그러한 리디렉션을 시도 할 때 발생했던 문제이므로 여기에 있습니다.
ashrasmun

5

cout 을 파일 로 리디렉션하려면 이것을 시도 하십시오.

#include <iostream>
#include <fstream>

int main()
{
    /** backup cout buffer and redirect to out.txt **/
    std::ofstream out("out.txt");

    auto *coutbuf = std::cout.rdbuf();
    std::cout.rdbuf(out.rdbuf());

    std::cout << "This will be redirected to file out.txt" << std::endl;

    /** reset cout buffer **/
    std::cout.rdbuf(coutbuf);

    std::cout << "This will be printed on console" << std::endl;

    return 0;
}

전체 기사 읽기 std :: rdbuf를 사용하여 cin 및 cout 리디렉션


1
이 질문은 거의 6 년 전 (2012 년)에 답변되었지만 2018 년에 지금 답변을 추가했습니다. 귀하의 답변은 수락 된 답변과 동일합니다. 당신이하지 않은 경우 궁금 해요 왜 당신이 게시 않았다 그래서 아무것도 새로운 추가를?
Nawaz

내 답변은 cout 버전만을 강조하고 자세한 답변은 아래 링크에 나와 있습니다.
HaseeB 미르

허용 된 답변 에없는 답변의 새로운 내용은 무엇입니까 ?
Nawaz

2
내 대답은 cout과 cin의 리디렉션을 혼합하지 않고 내 버전은 더 읽기 쉽도록 분리됩니다.
HaseeB Mir
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.