用c++ dup2写入文件

Write to file with C++ dup2

本文关键字:文件 dup2 c++      更新时间:2023-10-16

好了,我正在尝试从一个文件读取并写入另一个文件。

我还有其他的东西要添加,比如从第一个文件抓取信息,但为了测试,我试图让它写到第二个文件。

我的理解是dp2()调用之后的所有内容都将输出到第二个参数。对吧?

    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);
    }

首先,我不确定是什么使您相信您需要使用dup2()。不要在这里使用它,它不需要,会做错误的事情。

第二,要将输出写入低级文件描述符,使用write():
write(file2, "yeahn", 5);

用完后别忘了加close(file2)