Home > Backend Development > C++ > How Can I Redirect Both Standard Input and Output to Files in C ?

How Can I Redirect Both Standard Input and Output to Files in C ?

Barbara Streisand
Release: 2024-12-25 03:07:15
Original
493 people have browsed it

How Can I Redirect Both Standard Input and Output to Files in C  ?

Simultaneously Redirecting Input and Output to Files

One may desire to redirect the standard input and output streams to files for diverse reasons, such as collecting user data or performing batch processing. This article provides a comprehensive solution for achieving this in C .

Solution

The provided C code effectively demonstrates how to redirect the standard input (cin) to a designated file ("in.txt") and the standard output (cout) to a specified file ("out.txt"):

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

void f() {
  std::string line;
  while (std::getline(std::cin, line)) {  // input from "in.txt"
    std::cout << line << "\n";  // output to "out.txt"
  }
}

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

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

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

  f();  // call function

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

  std::cin >> word;  // input from standard input
  std::cout << word;  // output to standard output
}
Copy after login

To redirect both input and output in a single line:

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

This principle applies to any stream, allowing user input and program output to be managed conveniently.

The above is the detailed content of How Can I Redirect Both Standard Input and Output to Files in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template