0
std::string example;
int fd = open(argv[1], O_RDONLY);   //open file on file descriptor
int newfd = dup2(fd, 0);

//do stuff with file one then open file two
std::cin >> example;
std::cout << example << std:endl;

int fd2 = open(argv[2], O_RDONLY);  //open file2 on file descriptor
int newfd2 = dup2(fd2, 0);

std::cin >> example;
std::cout << example  << std:endl;

I've been looking for a solution to this for a while. Is there any way to open another file redirecting to stdin? This is assuming argv[1], argv[2] are files.

File1: abcdefg

File2: ABCDEFG

Expected Output:
abcdefg
ABCDEFG

Current Output:
abcdefg
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
ac4824
  • 17
  • 4
  • 2
    Your question is unclear. First of all, you are redirecting *stdin to a file*, not *a file to stdin* (which is the opposite). Secondly, are you trying to redirect stdin to *multiple* files at once? If so, please state it clearly. If not, elaborate on what you're trying to do. – Marco Bonelli Apr 07 '20 at 17:15
  • I want to use stdin on a single file then use it on another file – ac4824 Apr 08 '20 at 02:22
  • Again, it's still unclear. If you only want to "switch" file then the code you are showing already does exactly that. You need to explain clearly what you're trying to do. An example of the expected result after running the program would be a good idea. – Marco Bonelli Apr 08 '20 at 02:25
  • I know its supposed to "switch" the file but for some reason it doesn't. It doesn't even let restore stdin. I'll edit the question to show expected result – ac4824 Apr 08 '20 at 08:15
  • See Option 1, Note 2 [here](https://stackoverflow.com/a/46869216/5136580) – Mikel Rychliski Apr 15 '20 at 03:32

1 Answers1

0

You are mixing raw syscalls (open, dup2) with C++ standard library functions which offer very higher level operations. Since library functions do all kinds of magic in the background, mixing them with lower level functions or even raw syscalls can create trouble, since the latter modify the behavior of the program without giving the standard library a chance to acknowledge the change and update its internal data to match the modifications.

What you should do, is to either:

  1. Use only syscalls: open, dup2, read and write.
  2. Use only standard library functions (where possible): fopen, freopen, cin, cout, etc.

Your program should be rewritten like this:

std::string example;

freopen(argv[1], "r", stdin);
// Don't forget to check for errors.

std::cin >> example;
std::cout << example << std::endl;

freopen(argv[2], "r", stdin);
// Don't forget to check for errors.

std::cin >> example;
std::cout << example  << std::endl;
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128