From owner-freebsd-questions Wed Mar 11 15:58:42 1998 Return-Path: Received: (from majordom@localhost) by hub.freebsd.org (8.8.8/8.8.8) id PAA12033 for freebsd-questions-outgoing; Wed, 11 Mar 1998 15:58:42 -0800 (PST) (envelope-from owner-freebsd-questions@FreeBSD.ORG) Received: from allegro.lemis.com (allegro.lemis.com [192.109.197.134]) by hub.freebsd.org (8.8.8/8.8.8) with ESMTP id PAA12008 for ; Wed, 11 Mar 1998 15:58:29 -0800 (PST) (envelope-from grog@lemis.com) Received: from freebie.lemis.com (freebie.lemis.com [192.109.197.137]) by allegro.lemis.com (8.8.7/8.8.5) with ESMTP id KAA22974; Thu, 12 Mar 1998 10:28:26 +1030 (CST) Received: (from grog@localhost) by freebie.lemis.com (8.8.8/8.8.7) id KAA04407; Thu, 12 Mar 1998 10:28:25 +1030 (CST) (envelope-from grog) Message-ID: <19980312102825.28496@freebie.lemis.com> Date: Thu, 12 Mar 1998 10:28:25 +1030 From: Greg Lehey To: Doug White , Matthew Hagerty Cc: freebsd-questions@FreeBSD.ORG Subject: Re: open(), fopen(), and flock() References: <3.0.3.32.19980310163441.031536ec@smtp.net-link.net> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Mailer: Mutt 0.89i In-Reply-To: ; from Doug White on Wed, Mar 11, 1998 at 10:46:13AM -0800 WWW-Home-Page: http://www.lemis.com/~grog Organization: LEMIS, PO Box 460, Echunga SA 5153, Australia Phone: +61-8-8388-8286 Fax: +61-8-8388-8725 Mobile: +61-41-739-7062 Sender: owner-freebsd-questions@FreeBSD.ORG Precedence: bulk X-Loop: FreeBSD.ORG On Wed, 11 March 1998 at 10:46:13 -0800, Doug White wrote: > On Tue, 10 Mar 1998, Matthew Hagerty wrote: > >> Could someone tell me if you can use flock() to lock a file opened with >> fopen()? > > No; flock() wants a file descriptor; see the man page. Use open(), flock() > it, then fdopen() the descriptor if you want to use the f* functions. I > don't think fdopen() eats the file descriptor though, so you should be > able to flock() the descriptor all you want even after you fdopen() it. > >> Is there some reason to use fopen() over open() or vice/versa? Is there >> even any locking mechanisms in ANSI-C? > > fopen() lets you use the f* functions that take FILE* as arguments > (fprintf(), fscanf(), etc.) and lets you do file repositioning easily > (rewind() & friends). Otherwise you have to use read()/write() directly, > and they are kinda messy for complex file operations. They're kinda messy > in general. :) In fact, there's very little difference in usage between open/read/write/close and fopen/fread/fwrite/fclose. The big difference is in the fact that the f* functions are buffered library functions, whereas the others are system calls. This improves performance if you're accessing a lot of unaligned data (the normal case). It also makes locking impossible, since you're keeping private copies of the data. Greg To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-questions" in the body of the message