.. with little commentary aside. Target audience: new programmers. These tips are equally applicable in C and C++ programming environments.
1. Duplicating a file pointer
Steps: find the integer file descriptor associated with the file stream using fileno()
call, make a copy of the file descriptor using dup()
call, and finally associate the file stream with the duplicated file descriptor by calling fdopen()
.
FILE *fptr = fopen("file", "mode"); FILE *fptrcopy = fdopen( dup( fileno(fptr) ), "mode");
2. Capturing the exit code of a command that was invoked using popen()
Using pipes is one way of executing commands programmatically that are otherwise invoked from a shell. While pipes are useful in performing tasks other than executing shell commands, this tip is mainly about the exit code of a command (to figure out whether it succeeded or failed) that was executed using popen()
API.
To capture the exit code, simply use the value returned by pclose()
. This function call returns the termination status of the command that was executed as a child process. However the termination status of the child process is in the top 16 bits of the return value, so dividing the pclose()
return value by 256 gives the actual exit code of the command that was executed.
... FILE *ptr; int rc; if ((ptr = popen("ls", "r")) != NULL) { rc = pclose(ptr)/256; printf("\nls: exit code = %d", rc); } if ((ptr = popen("ls -W", "r")) != NULL) { rc = pclose(ptr)/256; printf("\nls -W: exit code = %d", rc); } ... % ./<executable> ls: exit code = 0 ls: illegal option -- W ls -W: exit code = 2
3. Converting an integer to a string
Standard C library has implementation for converting a string to an integer (atoi()
), but not for converting an integer to a string. One way to achieve the desired result is by using sprintf()
function call, which writes formatted data to a string.
int weight = 30; char *wtstr = malloc(sizeof(char) * 3); sprintf(wtstr, "%d", weight); ...
sprintf()
can also be used to convert data in other data types such as float, double to string. Also see: man page for snprintf()
.
4. Finding the length of a statically allocated array
When size was not specified explicitly, simply divide the total size of the array by the size of the first array element.
eg.,static const char *greeting[] = { "Hi", "Hello", "Hola", "Bonjour", "Namaste", "Ciao", "Ni Hao" }; int numgreetings = sizeof(greeting)/sizeof(greeting[0]);
After execution, numgreetings
variable holds a value of 7. Note that sizeof(greeting[0])
is actually the size of a pointer to a character array.
sizeof
is not a function, but an operator -- hence it is not necessary or required to use parentheses when using it.- Though not so useful, this is applicable even when the size was explicitly specified.
No comments:
Post a Comment