好吧我试图从一个文件中读取并写入另一个文件。
我还要添加其他内容,例如从第一个文件中获取信息但是为了测试我试图让它写入第二个文件。
我的理解是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);
}
答案 0 :(得分:0)
首先,我不确定是什么让您相信您需要使用dup2()
。不要在这里使用它,它不需要并且会做错事。
其次,要将输出写入低级文件描述符,请使用write()
:
write(file2, "yeah\n", 5);
完成后不要忘记close(file2)
。