C++ 如何撤消此代码上cin的重定向?
我在下面的代码中使用了dup2(),现在我在让cin从屏幕读取时遇到问题:C++ 如何撤消此代码上cin的重定向?,c++,io,stream,file-descriptor,C++,Io,Stream,File Descriptor,我在下面的代码中使用了dup2(),现在我在让cin从屏幕读取时遇到问题: #include <iostream> #include <memory> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string> #include <fstream> #include <array> #include <
#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;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括streambuf*stream_buffer_cin=cin.rdbuf()
不会保存流的状态,因此执行cin.rdbuf(stream\u buffer\u 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;
}
std::string getP_string(const char*cmd){
唯一的ptr输入(popen(cmd,“r”),pclose;
int backInput=dup(0);
dup2(fileno(input.get()),0);
streambuf*stream_buffer_cin=cin.rdbuf();
如果(!输入){
cerr Unrelated:不要将共享的
添加到字符串数组中,看看是否可以使用std::vector
。不要重定向然后再重新重定向,而是问问自己,“我从重定向中得到了什么?”以及“让代码复杂化值得吗?”您是否已尝试并拒绝正常打开文件并直接从文件流中读取?我正在尝试使用fgets,但在倒带文件时失败