C/C++
How do I resolve compiler error with my multi-lined macro in C
Nov 14th
Let us look at the following plain multi-lined and multi-statement macro.
#define SAY_HELLO() \
printf("Hi, There!\n"); \
printf("Nice to meet you\n");
If you use the above macro as shown below, you will encounter compilation errors.
if(manager)
SAY_HELLO();
else
printf("You are not my manager..Why should I care?\n");
The above code expands to the following and results in compilation error as “else” part of the code is detached from the actual “if” condition.
if(manager)
printf("Hi, There!\n");
printf("Nice to meet you\n");
else
printf("You are not my manager..Why should I care?\n");
If you attempt to wrap all the statements of macro in {…}, general usage of the macro will throw More >
How to swap two integers without using third variable
Nov 13th
The safest way to swap two variables without using third variable is to use XOR operation as shown below.
This example C program swaps integer values of two variables i and j.
[neo@techpulp ~]# cat iswap.c
#include <stdio.h>
int main(int argc, char *argv[])
{
int i = 10, j = 20;
printf("Before swap: i = %d, j = %d\n", i, j);
i = i^j;
j = i^j;
i = i^j;
printf("After swap: i = %d, j = %d\n", i, j);
return 0;
}
[neo@techpulp ~]# gcc iswap.c -o iswap
[neo@techpulp ~]# ./iswap
Before swap: i = 10, j = 20
After swap: More > How to get the names of all files in a directory in C
Nov 10th
The opendir(), readir() and closedir() library functions supported by C library can be used to get the names of files presented in a directory. The readdir() function should be invoked repeatedly to get all the files until it returns NULL. It returns a pointer to a structure dirent.
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file */
char d_name[256]; /* filename */
};
The following example program takes a directory name as command line arguments and prints the names More >
Print IP address in dotted-decimal format without converting to string in C
Nov 10th
Few binary operations can be used to print a binary IP address in human-readable dotted-decimal format without using inet_ntoa() function that requires a string buffer. The following example shows how to do it.
[neo@techpulp ~]# cat pip.c
#include <stdio.h>
#define IP_QUAD(ip) (ip)>>24,((ip)&0x00ff0000)>>16,((ip)&0x0000ff00)>>8,((ip)&0x000000ff)
int main(int argc, char *argv[])
{
unsigned long my_ip = 0xa0653b20;
printf("My IP Address (0x%x) is %d.%d.%d.%d\n", my_ip, IP_QUAD(my_ip));
return 0;
}
[neo@techpulp ~]#
In the above program the macro IP_QUAD uses right-shift operator to extract each byte of the integer from MSB to LSB to expand it in to four arguments. This macro can be used pretty easily with “%u.%u.%u.%u” More >
How to write a function that takes variable number of arguments in C
Nov 10th
The C language supports function that takes variable number of arguments using standard argument interface (stdarg.h). The following are the functions used to handle variable number of arguments in a function.
#include <stdarg.h> void va_start(va_list ap, last); type va_arg(va_list ap, type); void va_end(va_list ap); void va_copy(va_list dest, va_list src);
The prototype of a function which takes varying number of arguments will be similar to the following.
int max_of(int count,int num1,...);
It is declared similar to any other function but a “…” is followed by fixed arguments representing the start of variable number of arguments. The varying number of arguments supplied to such function can More >
Parse date and time represented in custom string in C
Nov 10th
The C library function strptime() can be used to convert date and time represented in custom string format to a broken-down representation in struct tm. Here is the declaration of strptime() function.
char *strptime(const char *s, const char *format, struct tm *tm);
The following example parses a date and time string “2008-12-31 21:45:10” and converts first in to broken-down time format struct tm. Then converts it back to string format in another representation.
[neo@techpulp ~]# cat parse_time.c
#include <stdio.h>
#include <time.h>
char *times[] = {
"2008-12-31 21:45:10",
NULL
};
int main(int argc, char *argv[])
{
struct tm tm;
char buf[255];
strptime("2008-12-31 21:45:10", "%Y-%m-%d %H:%M:%S", &tm); More > How to get custom formatted date and time string in C
Nov 10th
The C library function strftime() can be used to print date and time in string format. This function converts a broken-down date and time represented by struct tm according to the given format specification. The other library functions time() and localtime() can be used to get the time in broken-down format. The following example get the current time and converts in to a string format and prints it on the screen.
[neo@techpulp ~]# cat mytime.c
#include <stdio.h>
#include <time.h>
int main(int argc, char *argv[])
{
time_t t;
struct tm *tm;
char buf[255];
time(&t);
tm = localtime(&t);
strftime(buf, sizeof(buf), "%d %b %Y %H:%M", tm);
puts(buf);
return More > How to get system uptime in C
Nov 7th
The sysinfo system call can be used to retrieve current system up-time. The function get_uptime() in the following code snippet returns system uptime in seconds.
[neo@techpulp ~]$ cat uptime.c
#include <stdio.h>
#include <sys/sysinfo.h>
long get_uptime(void)
{
struct sysinfo sinfo;
sysinfo(&sinfo);
return (sinfo.uptime);
}
int main(int argc, char *argv[])
{
printf("System is up for %ld seconds\n", get_uptime());
return 0;
}
The following shows the ouput of the above C example program.
[neo@techpulp ~]# gcc uptime.c -o uptime [neo@techpulp ~]# ./uptime System is up for 374080 seconds [neo@techpulp ~]# [neo@techpulp ~]# ./uptime System is up for 374085 seconds [neo@techpulp ~]#
More >
How to extract IP address from a string in C
Nov 5th
The library function inet_aton can be used to extract IP address from a string format (eg: “123.23.42.76″). This function returns non-zero value if the IP address is valid and zero if it is an invalid IP address. The following example shows how to use this library function.
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
char *ips[] = {
"12.34.56.7",
"123.123.123.123",
"255.255.255.255",
"345.123.23.54",
NULL
};
int main(int argc, char *argv[])
{
int i;
struct in_addr ia;
i = 0;
while(ips[i]) {
if(inet_aton(ips[i],&ia) == 0) {
printf("%s is an INVALID ip address\n", ips[i]);
} else {
printf("%s is a VALID ip address. 0x%lx\n", More > How to determine if a string contains a validate IP address in C
Oct 18th
Any valid IP address consists of four numbers separated by three period (.) characters and each number ranges from 0-255 inclusive. An example IP address is “125.231.167.234″. The string function sscanf can be used to extract the four numbers and then validate each number for the range 0-255. Then use strcmp to further validate with reconstructed ip string.
The following function returns 0 if the IP address is invalid and 1 if valid.
int is_valid_ip(const char *ip_str)
{
unsigned int n1,n2,n3,n4;
if(sscanf(ip_str,"%u.%u.%u.%u", &n1, &n2, &n3, &n4) != 4) return 0;
if((n1 != 0) && (n1 <= 255) && (n2 <= 255) && (n3 More > 

Recent Comments