Help
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
Copilot Lvl 2
Message 1 of 2

How does C open() function second and third parameters work ?

Solved! Go to Solution.

Hello everyone,

 

I've been looking for this for about an hour on google (and in these forums), I couldn't find an answer.
I apologize if the question had already been asked.
The question is : how do you send multiple macros to a function as a single parameter ?
Just like in the open() man code example :

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

#define LOCKFILE "/etc/ptmp"
...
    int pfd; /* Integer for file descriptor returned by open() call. */
    ...
    if ((pfd = open(LOCKFILE, O_WRONLY | O_CREAT | O_EXCL,
                    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
    {
        fprintf(stderr, "Cannot open /etc/ptmp. Try again later.\n");
        exit(1);
    }
...

How can I catch a parameter of this type : MACRO_1 | MACRO_2 ... ?

Have a great day/evening/night/whatever is true for you ! :D

PS: maybe the title is not that good... :smileyindifferent:

 

1 Reply
Solution
Copilot Lvl 2
Message 2 of 2

Re: How does C open() function second and third parameters work ?

Got an answer.

The pipe ( '|' symbol ) is a binary 'OR'.
It adds the different macros.
This means that to use this, the macros have to have binary values of 0b0001, 0b0010, 0b0100, 0b1000, etc...
Example :

#include <stdio.h> //for printf()

#define MACRO1 0b00000001 //equals decimal 1
#define MACRO2 0b00000010 //= decimal 2
#define MACRO3 0b00000100 //= 4
#define MACRO4 0b00001000 //8
#define MACRO5 0b00010000 //16
#define MACRO6 0b00100000 //32
#define MACRO7 0b01000000 //64
#define MACRO8 0b10000000 //128

int my_function(int flags)
{
    printf("%d\n", flags);
    //test flags value and do something.
}

int main(void)
{
    my_function(MACRO3 | MACRO4);
    my_function(MACRO1 | MACRO7);
    my_function(MACRO5);
}

Will output :

12
65
16



Hope it's clear enough !