如何撤消此代码上的 cin 重定向?
How to undo redirect of cin on this code?
我在下面的代码中使用了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;
}
相关文章:
- 如何将stdout重定向到stderr
- 编写时C++中的输入重定向问题
- 获取通过重定向传入的输入文件的名称?
- Windows C++重定向库
- 写入文件 a.txt,而终端重定向到文件 b.txt
- 使用 dup2() 进行输入重定向
- 将 clangd stderr 重定向到文件而不是控制台
- 如何在C++中获取重定向网页的URL
- 将标准输出重定向到ostream
- 如何撤消此代码上的 cin 重定向?
- 使用重定向标准处理子进程中的 kbhit
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- 重定向输入和输出时如何处理主文件I/O?
- 如何使用重定向的标准输入读取文件,即cin(注意:不使用ifstream)
- C++ 无法让 cin 从文件重定向中读取结束行字符
- 将cin重定向到c++中的字符串
- 将std::cin直接重定向到std::cout
- std::cin.rdbuf(in.rdbuf())导致重定向崩溃
- 如何重定向cout和cin
- 是否有重定向(cin)输入从文本文件在控制台两次,为c++