Request code for log-file mechanism

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Thu Oct 18 15:45:03 AEST 1990


In article <1990Oct17.094623.2381 at westc.uucp> marco at 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.



More information about the Comp.lang.c mailing list