c – 使用O_RDWR和O_RDONLY | O_WRONLY

前端之家收集整理的这篇文章主要介绍了c – 使用O_RDWR和O_RDONLY | O_WRONLY前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我简单的程序中:
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sstream>

using namespace std;

int main(int argc,char *argv[]) {
    stringstream ss;
    ss << "What does the quick brown fox say?" << endl;

    int file_descriptor = open("/dev/tty",O_RDONLY | O_WRONLY);
    write(file_descriptor,ss.str().c_str(),ss.str().size());
}

我使用O_RDONLY |的组合打开终端流O_WRONLY,这似乎工作正常.我得到你应该使用O_RDWR,因为它使得更清晰的语义感觉,但我的问题是为什么如果加入两个现有的标志已经工作,打算创建一个整个其他标志?这是有一些历史原因,还是我只是忽略某些东西,这真的不行吗?

@H_301_7@解决方法
O_RDONLY | O_WRONLY(至少在我的Linux机器上)与O_RDWR不一样.
#define O_RDONLY         00
#define O_WRONLY         01
#define O_RDWR           02

事实上,它的工作原理似乎是一个bug /功能/巧合,而不是“它的工作原理,因为它应该这样工作”.

猜你在找的C&C++相关文章