Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

posix - Function overloading in C

Today, looking at the man page for open(), I've noticed this function is 'overloaded':

   int open(const char *pathname, int flags);
   int open(const char *pathname, int flags, mode_t mode);

I didn't thought it's possible on C. What's the 'trick' for achieving this ?

LATER EDIT:
So it's not really overloading, because when using varargs - you can only supply multiple arguments of the same type. So, is mode_t behind the scenes an int ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's using variable arguments. Those declarations appear only in the man page, as those 2 are the only ways you should call open(). The actual C function will be declared as e.g.

int open(const char *pathname,int flags,...);

With variable arguments, the arguments don't need to be the same type. printf is the obvious example of this.

In the case of open(), the first variable argument have to be mode_t if 'flags contain the O_CREAT flag because implementation of open() expects it to be mode_t (which behind the scenes is likely an unsigned int or unsigned long - but that has nothing to do with varargs)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...