Xref: utzoo comp.lang.c:32962 comp.unix.programmer:274 Path: utzoo!utgpu!watserv1!watmath!att!rutgers!apple!uokmax!munnari.oz.au!goanna!ok From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) Newsgroups: comp.lang.c,comp.unix.programmer Subject: Re: Request code for log-file mechanism Keywords: c log-file source Message-ID: <4006@goanna.cs.rmit.oz.au> Date: 18 Oct 90 05:45:03 GMT References: <1990Oct17.094623.2381@westc.uucp> <1990Oct17.213140.19516@decuac.dec.com> Followup-To: comp.lang.c Organization: Comp Sci, RMIT, Melbourne, Australia Lines: 38 In article <1990Oct17.094623.2381@westc.uucp> marco@westc.uucp (Marco Nijdam) writes: >We are writing an application that must keep a log-file of the >actions that where taken. It is possible that more than one >process writes to a log file at the same time. Not only that, they wanted it *portable*. You're in luck. ANSI C comes pretty close to what you want. Open the log file: FILE *log = fopen(LogFileTitle, "a"); Ensure that the buffer is big enough for the longest message: size_t MaxLogLineLength = {whatever}; char *log_buffer = malloc(MaxLogLineLength+1); After having checked everything, set up the buffer: setvbuf(log, log_buffer, _IOLBF, MaxLogLineLength+1); Now, to write a record to the log file: fprintf(log, "{format}\n, {arguments}); What's going on here? The "a" argument of fopen() says "the file position indicator is positioned at the end of the file before EACH write". Making the buffer big enough for the longest line and selecting line buffering ensures that each time you write a line using fprintf(), the whole line will be buffered and then sent out. You really need to check the fine print, but this *should* work reasonably well. That is, after all, why "a" is defined the way it is. For anything more reliable, you will have to rely on file locking. -- Fear most of all to be in error. -- Kierkegaard, quoting Socrates.