我们知道,标记位赋予的值不同,就会生成不同的选项。那么如何给一个变量的位置赋予多个值呢?
int整型有32个比特位,故我们可以通过改变位的方式改变值的大小
示例:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define ONE 0x1 //0000 0001
#define TWO 0x2 //0000 0010
#define THREE 0x4 //0000 0100
void show(int flags)
{
if(flags & ONE) printf("hello one\n"); //0000 0011 & 0000 0001 = 0000 0001
if(flags & TWO) printf("hello two\n");
if(flags & THREE) printf("hello three\n");
}
int main()
{
show (ONE);
printf("------------------------------------------------------------------------\n");
show (TWO);
printf("------------------------------------------------------------------------\n");
show (ONE | TWO); //0000 0001 | 0000 0010 = 0000 0011
printf("------------------------------------------------------------------------\n");
show (ONE | TWO | THREE); //0000 0001 | 0000 0010 | 0000 0100 = 0000 0111
printf("------------------------------------------------------------------------\n");
return 0;
}
输出结果:
故:我们可知,想要赋给flags标志位多个值,就得用|
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd = open("log.txt",O_WRONLY | O_CREAT);//既创建又写入
if(fd < 0)
{
perror("open");
return 1;
}
//open success
printf("open success,fd: %d\n",fd);
return 0;
}