1

Alright I am trying to read from one file and write to another.

I have other things to add such as grabbing info from the first file but for testing I am trying to get it to write to the second file.

My understanding was that everything after the dp2() call would output to the second param. Right?

    using namespace std;
    using std::string;
    using std::ostream;
    using std::endl;
    string str;



    int main(){


    int file= open("./input.txt", O_CREAT | O_RDWR | O_APPEND, S_IRUSR | S_IWUSR);
        if(file==-1){
            cout<<"Error: "<<errno<<endl;
        }
    int file2= open("./output.txt", O_CREAT | O_RDWR | O_APPEND, S_IRUSR | S_IWUSR);
        if(file2==-1){
            cout<<"Error: "<<errno<<endl;
        }

    int retval = dup2(file,file2);
        if(retval == -1){
        cout<<"Error: "<<errno;
        }

    printf("yeah");


    close(file);

    }
user975044
  • 375
  • 4
  • 11
  • 26

1 Answers1

0

First, I'm not sure what led you to believe that you need to use dup2(). Don't use it here, it's not needed and will do the wrong thing.

Second, to write output to a low-level file descriptor, use write():

write(file2, "yeah\n", 5);

Don't forget to close(file2) when you're done with it.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • mm well that was easy, my teacher was actually the one to tell us to use it – user975044 Oct 18 '11 at 04:58
  • Well, if you *want* to use `printf`, then you can actually `dup2(file, 1)` which makes file descriptor 1 (stdout) write to your newly opened file. But doing so is a bit tricky and unusual, because once you do that you can't write to the original stdout anymore (unless you also save it somewhere else). I'd stick with `write()` for a simple program. – Greg Hewgill Oct 18 '11 at 05:19