C Library-cstdlib

String conversion

atof

double atof ( const char * str );

Convert string to double

Parses the C string str interpreting its content as a floating point number and returns its value as a double.
解析C字符串str,将其内容解释为浮点数,并以双精度返回其值。

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax resembling that of floating point literals, and interprets them as a numerical value. The rest of the string after the last valid character is ignored and has no effect on the behavior of this function.
函数首先根据需要丢弃尽可能多的空白字符,直到找到第一个非空白字符为止。然后,从这个字符开始,按照类似浮点文字的语法,取尽可能多的有效字符,并将其解释为数值。最后一个有效字符之后的其余字符串将被忽略,并且对该函数的行为没有影响。

A valid floating point number for atof is formed by a succession of:
atof的有效浮点数由以下各项组成:

An optional plus or minus sign 
A sequence of digits, optionally containing a decimal-point character 
An optional exponent part, which itself consists on an 'e' or 'E' character followed by an optional sign and a sequence of digits. 
可选的加号或减号
一系列数字,可选择包含小数点字符
一个可选的指数部分,它本身由一个“e”或“e”字符组成,后面跟着一个可选符号和一系列数字。
If the first sequence of non-whitespace characters in str does not form a valid floating-point number as just defined, or if no such sequence exists because either str is empty or contains only whitespace characters, no conversion is performed.
如果str中的第一个非空白字符序列不是刚才定义的有效浮点数,或者由于str为空或仅包含空白字符而不存在这样的序列,则不执行转换。
Parameters
str 
C string beginning with the representation of a floating-point number. 

Return Value
On success, the function returns the converted floating point number as a double value.
If no valid conversion could be performed, or if the correct value would cause underflow, a zero value (0.0) is returned.
If the correct value is out of the range of representable values, a positive or negative HUGE_VAL is returned.
成功后,函数将转换后的浮点数作为双值返回。

如果无法执行有效的转换,或者如果正确的值会导致下溢,则返回零值(0.0)。

如果正确的值超出可表示值的范围,则返回正或负HUGE_VAL。
Example
/* atof example: sine calculator */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main ()
{
  double n,m;
  double pi=3.1415926535;
  char szInput [256];
  printf ( "Enter degrees: " );
  gets ( szInput );
  n = atof ( szInput );
  m = sin (n*pi/180);
  printf ( "The sine of %f degrees is %f\n" , n, m );
  return 0;
}
 

Output:

Enter degrees: 45
The sine of 45.000000 degrees is 0.707101  

atoi

int atoi ( const char * str ); <cstdlib> 

Convert string to integer

Parses the C string str interpreting its content as an integral number, which is returned as an int value.
解析C字符串str,将其内容解释为整数,该整数作为int值返回。
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.


Parameters
str 
C string beginning with the representation of an integral number. 

Return Value
On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.
成功后,函数将转换后的整数作为int值返回。

如果无法执行有效的转换,则返回零值。

如果正确的值超出可表示值的范围,则返回INT_MAX或INT_MIN。

Example
/* atoi example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i;
  char szInput [256];
  printf ("Enter a number: ");
  fgets ( szInput, 256, stdin );
  i = atoi (szInput);
  printf ("The value entered is %d. The double is %d.\n",i,i*2);
  return 0;
}
 

Output:

Enter a number: 73
The value entered is 73. The double is 146. 

atol

long int atol ( const char * str ); <cstdlib> 

Convert string to long integer

Parses the C string str interpreting its content as an integral number, which is returned as a long int value.
解析C字符串str,将其内容解释为整数,该整数作为长int值返回

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
函数首先根据需要丢弃尽可能多的空白字符,直到找到第一个非空白字符为止。然后,从这个字符开始,取一个可选的初始加号或减号,后跟尽可能多的数字,并将其解释为数值。

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
字符串可以在构成整数的字符之后包含其他字符,这些字符将被忽略,对该函数的行为没有影响。

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
如果str中的第一个非空白字符序列不是有效的整数,或者由于str为空或仅包含空白字符而不存在这样的序列,则不执行转换。


Parameters
str 
C string containing the representation of an integral number. 

Return Value
On success, the function returns the converted integral number as a long int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, LONG_MAX or LONG_MIN is returned.
如果正确的值超出可表示值的范围,则返回LONG_MAX或LONG_MIN。

Example
/* atol example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  long int li;
  char szInput [256];
  printf ("Enter a long number: ");
  gets ( szInput );
  li = atol (szInput);
  printf ("The value entered is %d. The double is %d.\n",i,i*2);
  return 0;
}
 

Output:

Enter a number: 567283
The value entered is 567283. The double is 1134566. 

strtod

double strtod ( const char * str, char ** endptr ); <cstdlib> 

Convert string to double

Parses the C string str interpreting its content as a floating point number and returns its value as a double. If endptr is not a null pointer, the function also sets the value pointed by endptr to point to the first character after the number.
解析C字符串str,将其内容解释为浮点数,并以双精度返回其值。如果endptr不是空指针,函数还会将endptr指向的值设置为指向数字后的第一个字符。

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax resembling that of floating point literals, and interprets them as a numerical value. A pointer to the rest of the string after the last valid character is stored in the object pointed by endptr.
函数首先根据需要丢弃尽可能多的空白字符,直到找到第一个非空白字符为止。然后,从这个字符开始,按照类似浮点文字的语法,取尽可能多的有效字符,并将其解释为数值。指向最后一个有效字符之后字符串其余部分的指针存储在endptr指向的对象中。

A valid floating point number for strtod is formed by a succession of:


An optional plus or minus sign 
A sequence of digits, optionally containing a decimal-point character 
An optional exponent part, which itself consists on an 'e' or 'E' character followed by an optional sign and a sequence of digits. 
If the first sequence of non-whitespace characters in str does not form a valid floating-point number as just defined, or if no such sequence exists because either str is empty or contains only whitespace characters, no conversion is performed.
可选的加号或减号
一系列数字,可选择包含小数点字符
一个可选的指数部分,它本身由一个“e”或“e”字符组成,后面跟着一个可选符号和一系列数字。
如果str中的第一个非空白字符序列不是刚才定义的有效浮点数,或者由于str为空或仅包含空白字符而不存在这样的序列,则不执行转换。

Parameters
str 
C string beginning with the representation of a floating-point number. 
endptr 
Reference to an already allocated object of type char*, whose value is set by the function to the next character in str after the numerical value.
This parameter can also be a null pointer, in which case it is not used.


Return Value
On success, the function returns the converted floating point number as a double value.
If no valid conversion could be performed, a zero value (0.0) is returned.
If the correct value is out of the range of representable values, a positive or negative HUGE_VAL is returned, and the global variable errno is set to ERANGE.
If the correct value would cause underflow, zero is returned and errno is set to ERANGE.
如果正确的值超出了可表示值的范围,则返回正或负的HUGE_VAL,并且全局变量errno设置为ERANGE。
如果正确的值会导致下溢,则返回零,并将errno设置为ERANGE

Example
/* strtod example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  char szOrbits[] = "365.26 27.32";
  char * pEnd;
  double d1, d2;
  d1 = strtod (szOrbits,&pEnd);
  d2 = strtod (pEnd,NULL);
  printf ("The moon completes %.2lf orbits per Earth year.\n", d1/d2);
  return 0;
}
 

Output:

The moon completes 13.37 orbits per Earth year. 

strtol

long int strtol ( const char * str, char ** endptr, int base );

/* strtol example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
  char * pEnd;
  long int li1, li2, li3, li4;
  li1 = strtol (szNumbers,&pEnd,10);
  li2 = strtol (pEnd,&pEnd,16);
  li3 = strtol (pEnd,&pEnd,2);
  li4 = strtol (pEnd,NULL,0);
  printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
  return 0;
}
 

Output:

The decimal equivalents are: 2001, 6340800, -3624224 and 7340031 

strtoul

unsigned long int strtoul ( const char * str, char ** endptr, int base );

/* strtoul example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  char szInput [256];
  unsigned long ul;
  printf ("Enter an unsigned number: ");
  fgets (szInput,256,stdin);
  ul = strtoul (szInput,NULL,0);
  printf ("Value entered: %lu. Its double: %lu\n",ul,ul*2);
  return 0;
}

Pseudo-random sequence generation

rand

int rand ( void ); <cstdlib> 

Generate random number

Returns a pseudo-random integral number in the range 0 to RAND_MAX.
返回一个介于0到RAND_MAX之间的伪随机整数

This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using srand.
这个数字是由一种算法生成的,该算法每次调用它时都会返回一系列明显不相关的数字。该算法使用种子来生成序列,该序列应该使用srand初始化为一些不同的值。

RAND_MAX is a constant defined in <cstdlib>. Its default value may vary between implementations but it is granted to be at least 32767.
RAND_MAX是<cstdlib>中定义的常数。它的默认值可能在不同的实现中有所不同,但它被允许至少为32767。

A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range, which in most cases generates a good approximation to a random number. For example:
使用rand在确定的范围内生成伪随机数的典型方法是使用返回值乘以范围跨度的模,并将范围的初始值相加,在大多数情况下,这会生成对随机数的良好近似。例如:

( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014


Parameters
(none) 


Return Value
An integer value between 0 and RAND_MAX. 

Example
/* rand example: guess the number */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
  int iSecret, iGuess;

  /* initialize random seed: */
  srand ( time(NULL) );

  /* generate secret number: */
  iSecret = rand() % 10 + 1;

  do {
    printf ("Guess the number (1 to 10): ");
    scanf ("%d",&iGuess);
    if (iSecret<iGuess) puts ("The secret number is lower");
    else if (iSecret>iGuess) puts ("The secret number is higher");
  } while (iSecret!=iGuess);

  puts ("Congratulations!");
  return 0;
}

 

Output:

Guess the number (1 to 10): 5The secret number is higherGuess the number (1 to 10): 8The secret number is lowerGuess the number (1 to 10): 7Congratulations! 

srand

void srand ( unsigned int seed ); <cstdlib> 

Initialize random number generator

The pseudo-random number generator is initialized using the argument passed as seed.

For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.
Two different initializations with the same seed, instructs the pseudo-random generator to generate the same succession of results for the subsequent calls to rand in both cases.

If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.
如果seed设置为1,则生成器将重新初始化为其初始值,并产生与任何对rand或srand的调用之前相同的值。

In order to generate random-like numbers, srand is usually initialized to some distinctive value, like those related with the execution time. For example, the value returned by the function time (declared in header <ctime>) is different each second, which is distinctive enough for most randoming needs.


Parameters
seed 
An integer value to be used as seed by the pseudo-random number generator algorithm. 

Return Value
(none) 

Example
/* srand example */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
  printf ("First number: %d\n", rand() % 100);
  srand ( time(NULL) );
  printf ("Random number: %d\n", rand() % 100);
  srand ( 1 );
  printf ("Again the first number: %d\n", rand() %100);

  return 0;
}
 

Output:

First number: 41
Random number: 13
Again the first number: 41 

Dynamic memory management

calloc

void * calloc ( size_t num, size_t size ); <cstdlib> 

Allocate space for array in memory
为内存中的阵列分配空间

Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.
为num个元素的数组分配一块内存,每个元素的大小为字节长,并将其所有位初始化为零。

The effective result is the allocation of an zero-initialized memory block of (num * size) bytes.
有效的结果是分配了一个(num*size)字节的零初始化内存块。

Parameters
num 
Number of elements to be allocated. 
size 
Size of elements. 

Return Value
A pointer to the memory block allocated by the function.
The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a NULL pointer is returned.

Example
/* calloc example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i,n;
  int * pData;
  printf ("Amount of numbers to be entered: ");
  scanf ("%d",&i);
  pData = (int*) calloc (i,sizeof(int));
  if (pData==NULL) exit (1);
  for (n=0;n<i;n++)
  {
    printf ("Enter number #%d: ",n);
    scanf ("%d",&pData[n]);
  }
  printf ("You have entered: ");
  for (n=0;n<i;n++) printf ("%d ",pData[n]);
  free (pData);
  return 0;
}
 

This program simply stores numbers and then prints them out. But the number of items it stores can be adapted each time the program is executed because it allocates as much dynamic memory as needed during runtime.

free

void free ( void * ptr ); <cstdlib> 

Deallocate space in memory

A block of memory previously allocated using a call to malloc, calloc or realloc is deallocated, making it availbale again for further allocations.
先前使用malloc、calloc或realloc调用分配的内存块将被释放,使其再次可用于进一步的分配。

Parameters
ptr 
Pointer to a memory block previously allocated with malloc, calloc or realloc to be deallocated.
If a null pointer is passed as argument, no action occurs. 

Return Value
(none)

Example
/* free example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int * buffer1, * buffer2, * buffer3;
  buffer1 = (int*) malloc (100*sizeof(int));
  buffer2 = (int*) calloc (100,sizeof(int));
  buffer3 = (int*) realloc (buffer2,500*sizeof(int));
  free (buffer1);
  free (buffer3);
  return 0;
}
 

This program has no output. Just demonstrates some ways to allocate and free dynamic memory using the cstdlib functions.

malloc

void * malloc ( size_t size ); <cstdlib> 

Allocate memory block

Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.

The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.
新分配的内存块的内容未初始化,仍具有不确定的值。

Parameters
size 
Size of the memory block, in bytes. 

Return Value
On success, a pointer to the memory block allocated by the function.
The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a null pointer is returned.

Example
/* malloc example: string generator*/
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i,n;
  char * buffer;

  printf ("How long do you want the string? ");
  scanf ("%d", &i);

  buffer = (char*) malloc (i+1);
  if (buffer==NULL) exit (1);

  for (n=0; n<i; n++)
    buffer[n]=rand()%26+'a';
  buffer[i]='\0';

  printf ("Random string: %s\n",buffer);
  free (buffer);

  return 0;
}
 

realloc

void * realloc ( void * ptr, size_t size ); <cstdlib> 

Reallocate memory block
重新分配内存块

The size of the memory block pointed to by the ptr parameter is changed to the size bytes, expanding or reducing the amount of memory available in the block.
ptr参数所指向的内存块的大小将更改为字节大小,从而扩展或减少块中可用的内存量。

The function may move the memory block to a new location, in which case the new location is returned. The content of the memory block is preserved up to the lesser of the new and old sizes, even if the block is moved. If the new size is larger, the value of the newly allocated portion is indeterminate.
该函数可以将存储器块移动到新位置,在这种情况下,返回新位置。即使块被移动,内存块的内容也会保留到新大小和旧大小中较小的一个。如果新的大小较大,则新分配的部分的值是不确定的。

In case that ptr is NULL, the function behaves exactly as malloc, assigning a new block of size bytes and returning a pointer to the beginning of it.
在ptr为NULL的情况下,函数的行为与malloc完全一样,分配一个新的字节大小的块,并返回一个指向其开头的指针。

In case that the size is 0, the memory previously allocated in ptr is deallocated as if a call to free was made, and a NULL pointer is returned.
在大小为0的情况下,以前在ptr中分配的内存将被释放,就像调用了free一样,并返回NULL指针。


Parameters
ptr 
Pointer to a memory block previously allocated with malloc, calloc or realloc to be reallocated.
If this is NULL, a new block is allocated and a pointer to it is returned by the function. 
size 
New size for the memory block, in bytes.
If it is 0 and ptr points to an existing block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned. 

Return Value
A pointer to the reallocated memory block, which may be either the same as the ptr argument or a new location.
The type of this pointer is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a NULL pointer is returned. 

Example
/* realloc example: rememb-o-matic */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int input,n;
  int count=0;
  int * numbers = NULL;

  do {
     printf ("Enter an integer value (0 to end): ");
     scanf ("%d", &input);
     count++;
     numbers = (int*) realloc (numbers, count * sizeof(int));
     if (numbers==NULL)
       { puts ("Error (re)allocating memory"); exit (1); }
     numbers[count-1]=input;
  } while (input!=0);

  printf ("Numbers entered: ");
  for (n=0;n<count;n++) printf ("%d ",numbers[n]);
  free (numbers);

  return 0;
}
 

The program prompts the user for numbers until a zero character is entered. Each time a new value is introduced the memory block pointed by numbers is increased by the size of an int.

Environment

abort

void abort ( void ); <cstdlib> 

Abort current process
中止当前进程

Aborts the process with an abnormal program termination.
由于程序异常终止而中止进程。

The function generates the SIGABRT signal, which by default causes the program to terminate returning an unsuccessful termination error code to the host environment.
该函数生成SIGABRT信号,默认情况下会导致程序终止,并向主机环境返回一个不成功的终止错误代码。

The program is terminated without executing destructors for objects of automatic or static storage duration, and without calling any atexit function.
程序终止时不执行自动或静态存储持续时间对象的析构函数,也不调用任何atexit函数。

The function never returns to its caller.
函数永远不会返回给调用方。

Parameters
(none)

Return Value
(none)

Example
/* abort example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  FILE * pFile;
  pFile= fopen ("myfile.txt","r");
  if (pFile == NULL) 
  {
    fputs ("error opening file\n",stderr);
    abort();
  }

  /* regular process here */

  fclose (pFile);
  return 0;
}
 

If myfile.txt does not exist, a message is printed and abort is called.

atexit

int atexit ( void ( * function ) (void) ); <cstdlib> 

Set function to be executed on exit
设置要在退出时执行的功能
 
The function pointed by the function pointer argument is called when the program terminates normally.
当程序正常终止时,会调用函数指针参数所指向的函数。

If more than one atexit function has been specified by different calls to this function, they are all executed in reverse order as a stack, i.e. the last function specified is the first to be executed at exit.
如果该函数的不同调用指定了多个atexit函数,则它们都作为堆栈以相反的顺序执行,即指定的最后一个函数是在退出时执行的第一个函数。

One single function can be registered to be executed at exit more than once.
一个单独的函数可以注册为在出口处执行多次。

C++ implementations are required to support the registration of at least 32 atexit functions.
C++实现需要支持至少32个atexit函数的注册。


Parameters
function 
Function to be called. The function has to return no value and accept no arguments. 
要调用的函数。函数必须不返回任何值,也不接受任何参数。

Return Value
A zero value is returned if the function was successfully registered, or a non-zero value if it failed.
如果函数注册成功,则返回零值;如果失败,则返回非零值。

Example
/* atexit example */
#include <stdio.h>
#include <stdlib.h>

void fnExit1 (void)
{
  puts ("Exit function 1.");
}

void fnExit2 (void)
{
  puts ("Exit function 2.");
}

int main ()
{
  atexit (fnExit1);
  atexit (fnExit2);
  puts ("Main function.");
  return 0;
}
 

Output:

Main function.Exit function 2.Exit function 1. 

exit

void exit ( int status ); <cstdlib> 

Terminate calling process
终止调用进程

Terminates the process normally, performing the regular cleanup for terminating processes.
正常终止进程,对终止进程执行定期清理。

First, all functions registered by calls to atexit are executed in the reverse order of their registration. Then, all streams are closed and the temporary files deleted, and finally the control is returned to the host environment.
首先,通过调用atexit注册的所有函数都以注册的相反顺序执行。然后,关闭所有流并删除临时文件,最后将控制权返回到主机环境。

The status argument is returned to the host environment.
状态参数返回到主机环境。

Parameters
status 
Status value returned to the parent process. Generally, a return value of 0 or EXIT_SUCCESS indicates success, and any other value or the constant EXIT_FAILURE is used to indicate an error or some kind of abnormal program termination. 
返回到父进程的状态值。通常,返回值0或EXIT_SUCCESS表示成功,任何其他值或常量EXIT_FAILURE用于表示错误或某种异常程序终止。

Return Value
(none)

Example
/* exit example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  FILE * pFile;
  pFile = open ("myfile.txt","r");
  if (pFile==NULL)
  {
    printf ("Error opening file");
    exit (1);
  }
  else
  {
    /* file operations here */
  }
  return 0;
}
 

getenv

char * getenv ( const char * name ); <cstdlib> 

Get environment string

Retrieves a C string containing the value of the environment variable whose name is specified as argument. If the requested variable is not part of the environment list, the function returns a NULL pointer.

The string pointed by the pointer returned by this function shall not be modified by the program.

The same memory location may be used in subsequent calls to getenv, overwriting the previous content.


Parameters
name 
C string containing the name of the requested variable. 

Return Value
A null-terminated string with the value of the requested environment variable, or NULL if that environment variable does not exist.

Portability
Depending on the platform, this function may either be or not be case sensitive.

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

int main ()
{
  char * pPath;
  pPath = getenv ("PATH");
  if (pPath!=NULL)
    printf ("The current path is: %s",pPath);
  return 0;
}
 
The example above prints the PATH environment variable. 

system

int system ( const char * command ); <cstdlib> 

Execute system command

Invokes the command processor to execute a command. Once the command execution has terminated, the processor gives the control back to the program, returning an int value, whose interpretation is system-dependent.
调用命令处理器以执行命令。一旦命令执行终止,处理器将控制权交还给程序,返回一个int值,其解释取决于系统。

The function call also be used with NULL as argument to check whether a command processor exists.
函数调用还可以与NULL作为参数一起使用,以检查是否存在命令处理器。


Parameters
command 
C string containing the system command to be executed. 

Return Value
The value returned when the argument passed is not NULL, depends on the running environment specifications. In many systems, 0 is used to indicate that the command was succesfully executed and other values to indicate some sort of error.
When the argument passed is NULL, the function returns a nonzero value if the command processor is available, and zero otherwise.
传递的参数不为NULL时返回的值取决于运行的环境规范。在许多系统中,0用于指示命令已成功执行,其他值用于指示某种错误。
当传递的参数为NULL时,如果命令处理器可用,函数将返回一个非零值,否则返回零。

Portability
The behavior and return value are platform-dependent.

Example
/* system example : DIR */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int i;
  printf ("Checking if processor is available...");
  if (system(NULL)) puts ("Ok");
    else exit (1);
  printf ("Executing command DIR...\n");
  i=system ("dir");
  printf ("The value returned was: %d.\n",i);
  return 0;
}
 

Searching and sorting

bsearch

void * bsearch ( const void * key, const void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) );

Binary search in array

Searches the given key in the array pointed by base that is formed by num elements, each of a size of size bytes, and returns a void* pointer to the first entry in the table that matches the search key.
在由num个元素组成的base所指向的数组中搜索给定键,每个元素的大小为字节,并返回一个指向表中与搜索键匹配的第一个条目的void*指针。

To perform the search, the function compares the elements to the key by calling the function comparator specified as the last argument.
为了执行搜索,函数通过调用指定为最后一个参数的函数比较器,将元素与键进行比较。

Because this function performs a binary search, the values in the base array are expected to be already sorted in ascending order, with the same criteria used by comparator.
因为此函数执行二进制搜索,所以基数组中的值预计已经按照比较器使用的相同标准按升序排序。


Parameters
key 
Pointer to the object that serves as key for the search, type-casted as a void*. 
指向用作搜索关键字的对象的指针,键入casted作为void*。
base 
Pointer to the first object of the array where the search is performed, type-casted as a void*. 
指向执行搜索的数组的第一个对象的指针,键入casted作为void*。
num 
Number of elements in the array pointed by base. 
数组中由基数指向的元素数。
size 
Size in bytes of each element in the array. 
数组中每个元素的大小(以字节为单位)。
comparator 
Function that compares two elements. The function shall follow this prototype:
int comparator ( const void * elem1, const void * elem2 );
比较两个元素的函数。功能应遵循此原型:int比较器(const void*elem1,const void*elem2);

The function must accept two parameters that are pointers to elements, type-casted as void*. These parameters 函数必须接受两个参数,这两个参数是指向元素的指针,类型强制转换为void*。应该将这些参数强制转换回某个数据类型并进行比较。should be cast back to some data type and be compared.

The return value of this function should represent whether elem1 is considered less than, equal, or grater than elem2 by returning, respectivelly, a negative value, zero or a positive value.
该函数的返回值应通过分别返回负值、零或正值来表示elem1是否被认为小于、等于或大于elem2。

For types that support regular comparison operators, a general comparator function may look like:

int compareMyType (const void * a, const void * a)
{
  if ( *(MyType*)a >  *(MyType*)b ) return 1;
  if ( *(MyType*)a == *(MyType*)b ) return 0;
  if ( *(MyType*)a <  *(MyType*)b ) return -1;
}
 

Return Value
A pointer to an entry in the array that matches the search key.
If key is not found, a NULL pointer is returned. 

Example
/* bsearch example */
#include <stdio.h>
#include <stdlib.h>

int compareints (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}

int values[] = { 10, 20, 25, 40, 90, 100 };

int main ()
{
  int * pItem;
  int key = 40;
  pItem = (int*) bsearch (&key, values, 6, sizeof (int), compareints);
  if (pItem!=NULL)
    printf ("%d is in the array.\n",*pItem);
  else
    printf ("%d is not in the array.\n",key);
  return 0;
}
 

In the example there is an array of sorted int values. There is also a function called compare that compares the values pointed by the two parameters as if they were pointers to int values (which they indeed are) and returns the result of the subtraction of the values pointed by both, which gives 0 as result if they are equal, a positive result if the value pointed by a is greater than the pointed by b or a negative result if the value pointed by b is greater.

In the main, function there is a call to bsearch with 40 as key, so the function finds that key in the array of values and the program prints out:


40 is in the array. 


For C strings, strcmp can directly be used as the last argument for bsearch:
/* bsearch example with strings */
#include <stdio.h>
#include <stdlib.h>

char strvalues[][20] = {"some","example","strings","here"};

int main ()
{
  char * pItem;
  char key[20] = "example";

  /* sort elements in array: */
  qsort (strvalues, 4, 20, (int(*)(const void*,const void*)) strcmp);

  /* search for the key: */
  pItem = (char*) bsearch (key, strvalues, 4, 20, (int(*)(const void*,const void*)) strcmp);

  if (pItem!=NULL)
    printf ("%s is in the array.\n",pItem);
  else
    printf ("%s is not in the array.\n",key);
  return 0;
}
 

qsort

void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) );

Sort elements of array

Sorts the num elements of the array pointed by base, each element size bytes long, using the comparator function to determine the order.

The sorting algorithm used by this function compares pairs of values by calling the specified comparator function with two pointers to elements of the array.

The function does not return any value, but modifies the content of the array pointed by base reordering its elements to the newly sorted order.


Parameters
base 
Pointer to the first element of the array to be sorted. 
num 
Number of elements in the array pointed by base. 
size 
Size in bytes of each element in the array. 
comparator 
Function that compares two elements. The function shall follow this prototype:
int comparator ( const void * elem1, const void * elem2 );

The function must accept two parameters that are pointers to elements, type-casted as void*. These parameters should be cast back to some data type and be compared.

The return value of this function should represent whether elem1 is considered less than, equal, or grater than elem2 by returning, respectivelly, a negative value, zero or a positive value.



Return Value
(none) 

Example
/* qsort example */
#include <stdio.h>
#include <stdlib.h>

int values[] = { 40, 10, 100, 90, 20, 25 };

int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}

int main ()
{
  int n;
  qsort (values, 6, sizeof(int), compare);
  for (n=0; n<6; n++)
     printf ("%d ",values[n]);
  return 0;
}
 

Output:

10 20 25 40 90 100 

Integer arithmethics

abs

int abs ( int n );
long abs ( long n ); 

Absolute value

Returns the absolute value of parameter n ( /n/ ).


Parameters
n 
Integral value. 

Return Value
The absolute value of n.

Portability
In C, only the int version exists.

Example
/* abs example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int n,m;
  n=abs(23);
  m=abs(-11);
  printf ("n=%d\n",n);
  printf ("m=%d\n",m);
  return 0;
}
 

Output:

n=23
m=11 


div

div_t div ( int numerator, int denominator );
ldiv_t div ( long numerator, long denominator ); <cstdlib> 

Integral division

Returns the integral quotient and remainder of the division of numerator by denominator as a structure of type div_t or ldiv_t, which has two members: quot and rem.


Parameters
numerator 
Numerator. 
denom 
Denominator. 

Return Value
The result is returned by value in a structure defined in <cstdlib>, which has two members. For div_t, these are, in either order:
int quot; 
int rem; 
and for ldiv_t:
long quot; 
long rem; 


Portability
In C, only the int version exists.

Example
/* div example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  div_t divresult;
  divresult = div (38,5);
  printf ("38 div 5 => %d, remainder %d.\n", divresult.quot, divresult.rem);
  return 0;
}
 

Output:

38 div 5 => 7, remainder 3. 

labs

long int labs ( long int n ); <cstdlib> 

Absolute value

Returns the absolute value of parameter n ( /n/ ).


Parameters
n 
Integral value. 

Return Value
The absolute value of n.

Example
/* labs example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  long int n,m;
  n=labs(65537L);
  m=labs(-100000L);
  printf ("n=%ld\n",n);
  printf ("m=%ld\n",m);
  return 0;
}
 

Output:

n=65537
m=100000 

ldiv

ldiv_t ldiv ( long int numerator, long int denominator ); <cstdlib> 

Integral division

Returns the integral quotient and remainder of the division of numerator by denominator as a structure of type ldiv_t, which has two members: quot and rem.


Parameters
numerator 
Numerator. 
denom 
Denominator. 

Return Value
The result is returned by value in a ldiv_t structure (defined in <cstdlib>), which has two members, in either order:
long quot; 
long rem; 

Example
/* ldiv example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  ldiv_t ldivresult;
  ldivresult = ldiv (1000000L,132L);
  printf ("1000000 div 132 => %ld, remainder %ld.\n", ldivresult.quot, ldivresult.rem);
  return 0;
}
 

Output:

1000000 div 132 => 7575, remainder 100. 

Multibyte characters

mblen

int mblen ( const char * pmb, size_t max ); <cstdlib> 

Get length of multibyte character
获取多字节字符的长度

The size of the multibyte character pointed by pmb is determined, examining at most max bytes.
pmb所指向的多字节字符的大小已确定,最多检查最大字节数
mblen has its own internal shift state, which is altered as necessary only by calls to this function.
mblen有自己的内部移位状态,只有通过调用该函数才能根据需要进行更改。


Parameters
pmb 
Pointer to the first byte of a multibyte character.
指向多字节字符的第一个字节的指针。
Alternativelly, the function may be called with a null pointer, in which case the function resets its internal shift state to the initial value and returns whether multibyte characters have state-dependent encodings or not. 
或者,函数可以用空指针调用,在这种情况下,函数将其内部移位状态重置为初始值,并返回多字节字符是否具有状态相关编码。
max 
Maximum number of bytes to be checked for character length. No more than MB_CUR_MAX characters are examined in any case. 
要检查字符长度的最大字节数。在任何情况下,检查的字符都不超过MB_CUR_MAX。

Return Value 
If the argument passed as pmb is not a null pointer, the size in bytes of the character pointed by pmb is returned when it forms a valid multibyte character and is not the terminating null character. If it is the terminating null character, the function returns zero, and in the case they do not form a valid multibyte character, -1 is returned.
If the argument passed as pmb is a null pointer, the function returns a nonzero value if multibyte character encodings are state-dependent, and zero otherwise.
如果作为pmb传递的参数不是空指针,则当pmb所指向的字符形成有效的多字节字符并且不是终止的空字符时,将返回该字符的字节大小。如果它是终止的null字符,则函数返回零,如果它们不构成有效的多字节字符,则返回-1。

如果作为pmb传递的参数是空指针,则如果多字节字符编码依赖于状态,则函数返回非零值,否则返回零。

mbtowc

int mbtowc ( wchar_t * pwc, const char * pmb, size_t max ); <cstdlib> 

Convert multibyte character to wide character

The wchar_t equivalent of the multibyte character pointed by pmb is determined and stored in the location pointed by pwc. The length in bytes of the multibyte character pointed by pmb is returned.
mbtowc has its own internal shift state, which is altered as necessary only by calls to this function.


Parameters
pwc 
Pointer to an object of type wchar_t.
Alternativelly, this argument can be a null pointer, in which case the function does not store the wchar_t translation, but still returns the length in bytes of the multibyte character. 
pmb 
Pointer to the first byte of a multibyte character.
Alternativelly, this argument can be a null pointer, in which case the function resets its internal shift state to the initial value and returns whether multibyte characters have state-dependent encodings or not. 
max 
Maximum number of bytes to be checked for character length. No more than MB_CUR_MAX characters are examined in any case. 

Return Value 
If the argument passed as pmb is not a null pointer, the size in bytes of the character pointed by pmb is returned when it forms a valid multibyte character and is not the terminating null character. If it is the terminating null character, the function returns zero, and in the case they do not form a valid multibyte character, -1 is returned.
If the argument passed as pmb is a null pointer, the function returns a nonzero value if multibyte character encodings are state-dependent, and zero otherwise.

wctomb

int wctomb ( char * pmb, wchar_t character ); <cstdlib> 

Convert wide character to multibyte character

The wide character specified as second argument is translated to its multibyte equivalent and stored in the array pointed by pmb. The length in bytes of the equivalent multibyte character pointed by pmb is returned.
wctomb has its own internal shift state, which is altered as necessary only by calls to this function.


Parameters
pmb 
Pointer to an array large enough to hold a multibyte character, which at most is MB_CUR_MAX.
Alternativelly, the function may be called with a null pointer, in which case the function resets its internal shift state to the initial value and returns whether multibyte characters have state-dependent encodings or not. 
character 
Wide character of type wchar_t. 

Return Value 
If the argument passed as pmb is not a null pointer, the size in bytes of the character pointed by pmb is returned when it forms a valid multibyte character and is not the terminating null character. If it is the terminating null character, the function returns zero, and in the case they do not form a valid multibyte character, -1 is returned.
If the argument passed as pmb is a null pointer, the function returns a nonzero value if multibyte character encodings are state-dependent, and zero otherwise.

Multibyte strings

mbstowcs

size_t mbstowcs ( wchar_t * wcstr, const char * mbstr, size_t max ); <cstdlib> 

Convert multibyte string to wide-character string

The C multibyte character string mbstr is interpreted character by character and translated to its wchar_t equivalent, which is stored in the location pointed by wcstr. The length in characters of the resulting string, not including the ending null-character, is returned.


Parameters
wcstr 
Pointer to an array of wchar_t elements long enough to store a wide string max characters long. 
mbstr 
C multibyte character string to be interpreted. 
max 
Maximum number of wchar_t characters to be interpreted. 

Return Value 
The number of characters translated, not including the ending null-character.
If an invalid multibyte character is encountered, a -1 value is returned.

wcstombs

size_t wcstombs ( char * mbstr, const wchar_t * wcstr, size_t max ); <cstdlib> 

Convert wide-character string to multibyte string

The C wchar_t string wcstr is interpreted character by character and translated to its multibyte equivalent, which is stored in the location pointed by mbstr. The length in bytes of the resulting multibyte string, not including the ending null-character, is returned.


Parameters
mbstr 
Pointer to an array of char elements at least max bytes long. 
wcstr 
C wchar_t string to be trasnlated. 
max 
Maximum number of bytes to be written to mbstr. 

Return Value 
The number of bytes (not characters) translated and written to mbstr, not including the ending null-character.
If an invalid multibyte character is encountered, a -1 value is returned.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值