All notes
C

C functions

Time


// From /usr/include/time.h
struct tm
{
  int tm_sec;           /* Seconds. [0-60] (1 leap second) */
  int tm_min;           /* Minutes. [0-59] */
  int tm_hour;          /* Hours.   [0-23] */
  int tm_mday;          /* Day.     [1-31] */
  int tm_mon;           /* Month.   [0-11] */
  int tm_year;          /* Year - 1900.  */
  int tm_wday;          /* Day of week. [0-6] */
  int tm_yday;          /* Days in year.[0-365] */
  int tm_isdst;         /* DST.     [-1/0/1]*/

#ifdef  __USE_BSD
  long int tm_gmtoff;       /* Seconds east of UTC.  */
  __const char *tm_zone;    /* Timezone abbreviation.  */
#else
  long int __tm_gmtoff;     /* Seconds east of UTC.  */
  __const char *__tm_zone;  /* Timezone abbreviation.  */
#endif
};

time

Cplusplus. The value returned generally represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC (i.e., the current unix timestamp).


time_t time (time_t* timer);
// If the argument is not a null pointer, it also sets this value to the object pointed by timer.

typedef __time_t time_t;
// From /usr/include/bits/types.h
__STD_TYPE __TIME_T_TYPE __time_t;  /* Seconds since the Epoch.  */

localtime

Cplusplus.


struct tm * localtime (const time_t * timer);
// Convert time_t to tm as local time

time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
printf ("Current local time and date: %s", asctime(timeinfo));

// Output:
// Current local time and date: Wed Feb 13 17:17:11 2013

POSIX clock

C clock reports CPU time

http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock.html. POSIX c function clock() will time for CPU time.

To determine the time in seconds, the value returned by clock() should be divided by the value of the macro CLOCKS_PER_SEC. CLOCKS_PER_SEC is defined to be one million in time.h.

POSIX real/wall clock

http://www.informit.com/articles/article.aspx?p=23618&seqNum=8. In POSIX, sys/time.h defines a function gettimeofday, which writes out a struct timeval.

This structure represents a time, in seconds, split into two fields.

  1. The tv_sec field contains the integral number of seconds,
  2. and the tv_usec field contains an additional number of microseconds.

This struct timeval value represents the number of seconds elapsed since the start of the UNIX epoch, on midnight UTC on January 1, 1970.

http://stackoverflow.com/questions/17432502/how-can-i-measure-cpu-time-and-wall-clock-time-on-both-linux-windows.


//  Windows
#ifdef _WIN32
#include <Windows.h>
double get_wall_time(){
    LARGE_INTEGER time,freq;
    if (!QueryPerformanceFrequency(&freq)){
        //  Handle error
        return 0;
    }
    if (!QueryPerformanceCounter(&time)){
        //  Handle error
        return 0;
    }
    return (double)time.QuadPart / freq.QuadPart;
}
double get_cpu_time(){
    FILETIME a,b,c,d;
    if (GetProcessTimes(GetCurrentProcess(),&a,&b,&c,&d) != 0){
        //  Returns total user time.
        //  Can be tweaked to include kernel times as well.
        return
            (double)(d.dwLowDateTime |
            ((unsigned long long)d.dwHighDateTime << 32)) * 0.0000001;
    }else{
        //  Handle error
        return 0;
    }
}

//  Posix/Linux
#else
#include <sys/time.h>
double get_wall_time(){
    struct timeval time;
    if (gettimeofday(&time,NULL)){
        //  Handle error
        return 0;
    }
    return (double)time.tv_sec + (double)time.tv_usec * .000001;
}
double get_cpu_time(){
    return (double)clock() / CLOCKS_PER_SEC;
}
#endif

bcopy, bzero


#include <string.h>
// NOTE: It it deprecated. Use memcpy instead.
void bcopy(const void *src, void *dest, size_t n);

calloc, malloc

Difference between calloc and malloc

StackOverflow.

strftime

Cplusplus.


size_t strftime(char* ptr, size_t maxsize, const char* format, const struct tm* timeptr);
// maxsize: Maximum number of characters to be copied to ptr, including the terminating null-character.
// Return: If the length of the resulting C string, including the terminating null-character, doesn't exceed maxsize, the function returns the total number of characters copied to ptr (not including the terminating null-character). Otherwise, it returns zero, and the contents of the array pointed by ptr are indeterminate.

#include <stdio.h>      /* puts */
#include <time.h>       /* time_t, struct tm, time, localtime, strftime */

int main ()
{
	time_t rawtime;
	struct tm * timeinfo;
	char buffer[9];

	time (&rawtime);
	timeinfo = localtime (&rawtime);

	strftime(buffer, 7, "%I%M%p",timeinfo); // 0321PM
	puts (buffer);
	strftime(buffer, 9, "%Y%m%d", timeinfo); // 20150521
	puts (buffer);
	strftime(buffer, 7, "%H%M%S", timeinfo); // 152101
	puts (buffer);

	return 0;
}

Stackoverflow.


time_t t = time(NULL);
struct tm tm = *localtime(&t);

printf("now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);

getenv

Get environment variable value.


/* getenv example: getting path */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* getenv */

int main ()
{
  char* pPath;
	// char* getenv (const char* name);
  pPath = getenv ("PATH");
  if (pPath!=NULL)
    printf ("The current path is: %s",pPath);
  return 0;
}

Buffer overflow on the stack

Ref. The following code will produce buffer overflow:


char test[10];
int i;
for (i=0;i < 10000;i++) {
	test[i] = 'a';
}

It's not stack overflow

Ref. It's different from stack overflow. That is what happens when you recurse too deeply into a function, causing you to run out of stack frames.


int main(int argc, char *argv[]) {
    return main(argc, argv);
}

fread

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

Don't mistaken size and count


FILE *output = popen(cmdStr.c_str(), "r");
if (!output) {
	msg = "Err";
	retval = -1;
} else {
	const int textLen = 2000;
	char text[textLen];
	int msgLen=0;

	if (msgLen = fread(reinterpret_cast<void*>(text), 1, textLen, output) ) {
//	If change the position of "textLen" and "1", fread will read out nothing!
//	if (msgLen = fread(reinterpret_cast<void*>(text), text, 1, output) ) {
	}
	pclose(output);
	text[msgLen]='\0';

printf

Printf and flush

Stackoverflow.


printf("Buffered, will be flushed");
fflush(stdout); // Will now print everything in the stdout buffer

//you can also disable buffering on stdout by using setbuf:
setbuf(stdout, NULL);
Print binary

// Print binary in reverse order
void printBinary(int n)
{
  while (n) {
      if (n & 1)
          printf("1");
      else
          printf("0");
  
      n >>= 1;
  }
  printf("
");
}

printBinary(32766); // 011111111111111

sprintf

http://www.cplusplus.com/reference/cstdio/printf/.

%[flags][width][.precision][length]specifier,

Example:


#include <stdio.h>

int main()
{
	printf ("Characters: %c %c \n", 'a', 65);
	// Characters: a A
	printf ("Decimals: %d %ld\n", 1977, 650000L);
	// Decimals: 1977 650000
	printf ("Preceding with blanks: %10d \n", 1977);
	// Preceding with blanks:       1977
	printf ("Preceding with zeros: %010d \n", 1977);
	// Preceding with zeros: 0000001977
	printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
	// Some different radices: 100 64 144 0x64 0144
	printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
	// floats: 3.14 +3e+000 3.141600E+000
	printf ("Width trick: %*d \n", 5, 10);
	// Width trick:    10
	printf ("%s \n", "A string");
	// A string
	return 0;
}

// The following code is used to print MD5 string.
for (i=0; i<16; i++)
	printf("%02x", md5Str); // Print 32 chars.

sscanf

Read formatted data from string. On success, the function returns the number of items of the argument list successfully filled.

int sscanf ( const char * s, const char * format, ...);

scanf

Read formatted data from stdin.

int scanf ( const char * format, ... );

strtok

Ref.


int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

strlen

Ref. The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).


char mystr[100]="test string";
cout<<sizeof(mystr)<<endl; // evaluates to 100
cout<<strlen(mystr)<<endl; // returns 11.

system

http://my.oschina.net/renhc/blog/53580. Another good ref on ForkExecProcesses.

Replacement?

Reference.

strcmp


int strcmp ( const char * str1, const char * str2 );

Returns an integral value indicating the relationship between the strings:

<0	the first character that does not match has a lower value in ptr1
0 	the contents of both strings are equal
>0	the first character that does not match has a greater value in ptr1

strncmp


/** @brief Compares up to num characters of the C string str1 to those of the C string str2.
*/
int strncmp ( const char * str1, const char * str2, size_t num );

tolower, toupper, islower, isupper, isalnum, isalpha, isdigit


#include <cctype>
/**
	@retval The lowercase equivalent to c, if such value exists, or c (unchanged) otherwise.
*/
int tolower ( int c );

strcat


char * strcat ( char * destination, const char * source );

destination is returned.


/* strcat example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[80];
  strcpy (str,"these ");
  strcat (str,"strings ");
  strcat (str,"are ");
  strcat (str,"concatenated.");
  puts (str);
  return 0;
}

// Output:
// these strings are concatenated.

Language Reference

Keywords

static

There are two usages for the static keyword when defining variables:

Compilation/Translation Unit

SO.

A translation unit is the basic unit of compilation in C++. It consists of the contents of a single source file, plus the contents of any header files directly or indirectly included by it, minus those lines that were ignored using conditional preprocessing statements.

A single translation unit can be compiled into an object file, library, or executable program.

VA_list



// Codes from GhostScript "base/gsmisc.c".
int errprintf(const gs_memory_t *mem, const char *fmt, ...)
{
    int count;
    char buf[PRINTF_BUF_LENGTH];
    va_list args;

    va_start(args, fmt);
    count = vsnprintf(buf, sizeof(buf), fmt, args);
    if (count >= sizeof(buf) || count < 0)  { /* C99 || MSVC */
        errwrite(mem, buf, sizeof(buf) - 1);
        errwrite(mem, msg_truncated, sizeof(msg_truncated) - 1);
    } else {
        errwrite(mem, buf, count);
    }
    va_end(args);
    return count;
}