Penguin
Note: You are viewing an old revision of this page. View the current version.

This page describes some programming hints that might help you to write more portable C code.

File Handling

File locking

BSD-style unixes uses flock(2), which uses "advisory" locks. Ie, a process with sufficient read or write permission can ignore the lock and read/write a file. SysV-style unixes use either advisory locks or "mandatory" locks (if enabled in the filesystem), and access them by the fcntl(2) command and a struct flock object.

A more portable way (POSIX 1003.1-2001) is to use the lockf(3) function from unistd.h, which will do the correct type of locking for the unix it is compiled on. (In Linux/GNU libc, this function is a wrapper around fcntl(2)).

printf types

64bitisms and fixed sized types

If you have a fixed sized type (eg, uint64_t) and you want to use printf to display it, you need to know the real type of the integer. eg
uint64_t x; printf("%llu",x);
This however will fail on 64bit machines as uint64_t is "long" not "long long". The best solution to this that I've found is to typecast it to the longer of the types and use that. eg
uint64_t x; printf("%llu",(long long unsigned)x);

Better solutions solicited.


Part of CategoryProgramming