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

问题描述 投票:0回答:1

我在下面的代码中使用了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行)来自这里:how to undo dup2

c++ io stream file-descriptor
1个回答
0
投票

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.