> 백엔드 개발 > C++ > C 표준 입력 및 출력을 외부 파일로 리디렉션하는 방법은 무엇입니까?

C 표준 입력 및 출력을 외부 파일로 리디렉션하는 방법은 무엇입니까?

DDD
풀어 주다: 2024-12-19 00:03:10
원래의
622명이 탐색했습니다.

How to Redirect C   Standard Input and Output to External Files?

입력 및 출력을 외부 파일로 리디렉션

표준 입력(cin)의 입력 및 표준 출력(cout)의 출력을 외부 파일로 리디렉션 프로그램 동작을 테스트, 디버깅 또는 분석하는 데 유용한 기술입니다.

cin을 다음으로 리디렉션하려면 지정된 파일(예: in.txt):

  • 입력 파일에 대한 ifstream 개체를 엽니다.
  • cin.rdbuf()를 사용하여 cin과 관련된 이전 버퍼를 저장합니다. .
  • 다음을 사용하여 cin을 입력 파일의 버퍼로 리디렉션합니다. cin.rdbuf(in.rdbuf()).

cout을 지정된 파일(예: out.txt)로 리디렉션하려면:

  • cin을 리디렉션하는 것과 동일한 단계를 따르되 ofstream 객체와 cout.rdbuf()를 사용하세요. 대신.

예제 코드:

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

int main() {
    // Redirect cin to in.txt
    std::ifstream in("in.txt");
    std::streambuf *cinbuf = std::cin.rdbuf();
    std::cin.rdbuf(in.rdbuf());

    // Redirect cout to out.txt
    std::ofstream out("out.txt");
    std::streambuf *coutbuf = std::cout.rdbuf();
    std::cout.rdbuf(out.rdbuf());

    // Read and write to the redirected streams
    std::string line;
    while (std::getline(std::cin, line)) {
        std::cout << line << "\n";
    }

    // Reset to standard input and output
    std::cin.rdbuf(cinbuf);
    std::cout.rdbuf(coutbuf);
}
로그인 후 복사

참고: 다음을 사용하여 한 줄에 입력과 출력을 모두 리디렉션할 수도 있습니다. 다음 구문:

auto cinbuf = std::cin.rdbuf(in.rdbuf());
auto coutbuf = std::cout.rdbuf(out.rdbuf());
로그인 후 복사

위 내용은 C 표준 입력 및 출력을 외부 파일로 리디렉션하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿