Re: open(2) vs fopen(3)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




On Thu, 14 Sep 2006, moreau francis wrote:
> 
> I'm reading git source code and falling on this stupid question:
> Why sometime open(2) is used and other time fopen(3) is
> prefered. I'm sorry for this dump question but I have no clue.

fopen() tends to result in easier usage, especially if the file in 
question is a line-based ASCII file, and you can just use "fgets()" to 
read it. So fopen is the simple alternative for simple problems.

Using a direct open() means that you have to use the low-level IO 
functions (I'm ignoring the use of "fdopen()"), but if done right, it has 
a number of advantages:

 - with the proper use, it's potentially more efficient (but stdio is a 
   lot more efficient if you do lots of small writes without buffering)

 - you can control the creation flags better (ie if you want to do an 
   exclusive open, you _have_ to use "open()" - there's no portable way to 
   say O_EXCL with "fopen()")

 - error conditions are a lot more obvious and repeatable with the 
   low-level things, at least so I find personally. Error handling with 
   stdio routines is _possible_, but probably because almost nobody ever 
   does it, it's not something that people are conditioned to do, so it 
   ends up beign "strange".

   (So this third one is more a psychological issue than a really 
   technical issue - at least for me. I'd not use stdio for things I 
   might expect to do fsync() on, for example. It's _possible_, but very 
   non-intuitive, because that's now how people generally use stdio).

So it boils down to the fact that people tend to do higher-level things 
with stdio interfaces (fopen and friends), and lower-level things with the 
raw system call ("unistd.h") interfaces.

In git, you'd expect to see code that actually works on the object 
database or the refs using "open()" (both because it's low-level, and it 
generally wants to use O_EXCL and friends), and then things that open the 
".gitignore" file to use fopen() (because it's a line-based ASCII 
interface, and it's not an "important" file in the sense that we don't 
really care about some strange situation where it could give us an IO 
error).

There might also be a difference in personality. I probably tend to use 
the core unistd interfaces more than some other people would, and some 
other people might end up using stdio for pretty much everything.

			Linus
-
To unsubscribe from this list: send the line "unsubscribe git" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html

[Index of Archives]     [Linux Kernel Development]     [Gcc Help]     [IETF Annouce]     [DCCP]     [Netdev]     [Networking]     [Security]     [V4L]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux Security]     [Linux RAID]     [Linux SCSI]     [Fedora Users]