使用 C++ 写入文件杜普2
好吧,我正在尝试从一个文件读取并写入另一个文件。
我还有其他需要添加的内容,例如从第一个文件中获取信息,但为了测试我试图将其写入第二个文件。
我的理解是 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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我不确定是什么让您相信您需要使用
dup2()
。不要在这里使用它,它不是必需的,而且会做错误的事情。其次,要将输出写入低级文件描述符,请使用 write():
完成后不要忘记 close(file2)。
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()
:Don't forget to
close(file2)
when you're done with it.