如何撤消此代码上的 cin 重定向?

How to undo redirect of cin on this code?

本文关键字:cin 重定向 代码 何撤消 撤消      更新时间:2023-10-16

我在下面的代码中使用了dup2((,现在我在让cin从屏幕上读取时遇到了问题:

#include <iostream>
#include <memory>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <fstream>
#include <array>
#include <tuple>
using namespace std;
shared_ptr<string[]> getP_string(const char* cmd){
unique_ptr<FILE, decltype(&pclose)> input(popen(cmd, "r"), pclose);
int backInput = dup(0);
dup2(fileno(input.get()),0);
streambuf* stream_buffer_cin= cin.rdbuf();  
if(!input){
cerr << "won't open" << endl;
exit(EXIT_FAILURE);
}
int count=0;
int test;
for (test=fgetc(stdin); test!=EOF; test=fgetc(stdin)){
if (char(test) == 'n') count ++;
cout << (char)test;
}
shared_ptr<string[]> results(new string[count]);
cin.rdbuf(stream_buffer_cin); ///reading the cout above
for(int i=0;i<count;i++){
cin >> results[i];
}
close(fileno(input.get()));
dup2(backInput,0);
close(backInput);
return results;
}

我使用的部分内容(第 15、33、34 和 35 行(来自这里:如何撤消 dup2

streambuf* stream_buffer_cin = cin.rdbuf();

不会保存流的状态,因此这样做cin.rdbuf(stream_buffer_cin)不会倒带文件,只是将指针设置为同一内容。无需尝试倒带文件,只需使用会随着插入而增长的std::string

std::string getP_string(const char* cmd) {
unique_ptr<FILE, decltype(&pclose)> input(popen(cmd, "r"), pclose);
int backInput = dup(0);
dup2(fileno(input.get()), 0);
streambuf* stream_buffer_cin = cin.rdbuf();
if (!input) {
cerr << "won't open" << endl;
exit(EXIT_FAILURE);
}
std::string results;
std::copy(std::istreambuf_iterator<char>(std::cin), {},
std::back_inserter(results));
close(fileno(input.get()));
dup2(backInput, 0);
close(backInput);
return results;
}