jeudi 29 avril 2021

C++, how to open and close files properly?

I want to open some file, redirect the output their and go back to previous situation, so I wrote:

int fd = open("test.txt", O_WRONLY | O_CREAT, 0666);
dup(1);
dup2(3, 1);
close(3);
//call my func() to print in std::cout which will write to test.txt
dup2(4, 1);//Close file

I know that default input channel is in index 0, output channel (screen) in index 1 and stderr in index 2 so fd will get 3, dup 1 will create another pointer to output channel in index 4, then I replace screen with my file and close that isn't needed.

  1. My code is correct, but did I forget anything else or can it be made shorter/ more clear?

  2. Most importantly, in case one line fails I want to return false but this will be a lot of checks and in every advance step we need to close more... how can I solve this problem? what if I wanted in case of failure to make everything go back to its default situation?

Please Note, I only know and want to use open,close,dup,dup2

Aucun commentaire:

Enregistrer un commentaire