LINUX C function part

xiaoxiao2021-03-06  114

Isalnum (test character is English or number)

related functions

Isalpha, Isdigit, Islower, Isupper

Header file

#include

Definition function

Int IsalNum (INT C)

Function description

Check whether the parameter c is an English alphabet or arabic number, which is equivalent to using "Isalpha (C) || isdigit (c)" is tested in standard C.

return value

If the parameter C is a letter or a number, returns true, otherwise returns NULL (0).

Additional information

This is a macro definition, a non-real function.

example

/ * Find the string of characters in the STR string * / # @ ctype.h> main () {char str [] = "123c @ # fdsp [e?"; Int i; for (i = 0; STR [I]! = 0; i ) IF (isaly (STR [I])) Printf ("% c is an alphaenter character / n", str [i]);}

carried out

1 is an apphabetic character2 is an apphabetic character3 is an apphabetic characterc is an apphabetic characterF is an apphabetic characterD is an apphabetic characters is an apphabetic characterP is an apphabetic charactere is an apphabetic character

Isalpha (test character is English letters)

related functions

Isalnum, Islower, ISUPPER

Header file

#include

Definition function

Int Isalpha (INT C)

Function description

Check if the parameter c is English letters, which is equivalent to using "Isupper (C) || islower (c)" in standard C.

return value

Returns true if the parameter C is English letters, otherwise returns null (0).

Additional information

This is a macro definition, a non-real function.

example

/ * Find the string of characters in English letters * / # include main () {char str [] = "123c @ # fdsp [e?"; Int i; for (i = 0; STR [I]! = 0; i ) IF (isalpha (STR [I])) Printf ("% c is an alphapleric character / n", str [i]);}

carried out

C is an apphabetic characterd is an apphabetic characterd is an apphabetic characterp is an apphabetic charactere IS An apphabetic character

Isascii (testing characters are ASCII code characters)

related functions

Iscntrl

Header file

#include

Definition function

INT isascii (int C);

Function description

Check if the parameter c is an ASCII code character, that is, if it is determined whether c's range is between 0 and 127.

return value

Returns true if the parameter c is an ASCII code character, otherwise returns NULL (0).

Additional information

This is a macro definition, a non-real function.

example

/ * Judging whether INT i has an arbitrated ASCII code character * / # include main () {INT i; for (i = 125; i <130; i ) IF (ISASCII (I)) Printf "% d is an ascii character:% C / N", I, I); elseprintf ("% d is not an ascii character / n", i);}

125 is an ASCII Character: ~ 127 is an ASCII Character: 128 Is Not an Ascii Character129 Is Not an ASCII CHARACTER

Iscntrl (test character is the control character of ASCII code)

related functions

Isascii

Header file

#include

Definition function

INT ISCNTRL (INT C);

Function description

Check if the parameter C is an ASCII control code, that is, if it is determined whether or not the range of C is between 0 and 30.

return value

If the parameter C is an ASCII control code, returns true, otherwise returns NULL (0).

Additional information

This is a macro definition, a non-real function.

Isdigit (testing characters are Arabic)

related functions

Isxdigit

Header file

#include

Definition function

Int Isdigit (int C)

Function description

Check if the parameter C is a Arab number 0 to 9.

return value

If the parameter C is a arabic number, returns true, otherwise returns NULL (0).

Additional information

This is a macro definition, a non-real function.

example

/ * Find out the string of the Arabic number * / # include main () {char str [] = "123 @ # fdsp [e?"; Int i; for (i = 0; STR [I]! = 0; i ) IF (isdigit (STR [I])) Printf ("% C Is An Digit Character / N", STR [I]);}

carried out

1 IS An Digit Character2 Is An Digit Character3 IS An Digit Character

Isgraphis (Is the test character for printing characters)

related functions

Isprint

Header file

#include

Definition function

INT isgraph (int C)

Function description

Check if the parameter c is a printable character, if the ASCII code not mentioned is printed, and Non-space character returns TRUE.

return value

If the parameter C is a printable character, returns true, otherwise returns NULL (0).

Additional information

This is a macro definition, a non-real function.

example

/ * Judgment which of the STR string is a printable character * / include main () {char str [] = "A5 @;"; int i; for (i = 0; str [i]! = 0; I ) IF (ISGRAPH (STR [I])) Printf ("STR [% D] IS Printable Character:% D / N", I, STR [I]);}

carried out

STR [0] is Printable Character: Astr [1] Is Printable Character: 5Str [3] Is Printable Character: @str [4] Is Printable Character :;

Islower (testing characters is lowercase letters) related functions

Isalpha, Isupper

Header file

#include

Definition function

Int Islower (INT C)

Function description

Check if the parameter c is lowercase English letters.

return value

If the parameter c is a lowercase English letter, returns true, otherwise returns NULL (0).

Additional information

This is a macro definition, a non-real function.

example

#include main () {char str [] = "123 @ # fdsp [e?"; int i; for (i = 0; STR [I]! = 0; i ) IF (Islower (STR [i])) Printf ("% c is a lower-case character / n", STR [I]);}

carried out

C Is a Lower-Case Characters Is A Lower-Case Charactere Is A Lower-Case Character

Isprint (Test Character is (no is a printable character)

related functions

ISGRAPH

Header file

#include

Definition function

INT isprint (int C);

Function description

Check if the parameter c is a printable character, if the ASCII code not mentioned can be printed, the TRUE is returned.

return value

If the parameter C is a printable character, returns true, otherwise returns NULL (0).

Additional information

This is a macro definition, a non-real function.

example

/ * Judging which of the Str strings contain space characters * / # include main () {char str [] = "a5 @;"; int i; for (i = 0; STR [ I]! = 0; i ) IF (ISPRINT (STR [I])) Printf ("STR [% D] IS Printable Character:% D / N", I, STR [I]);}

carried out

STR [0] IS Printable Character: Astr [1] Is Printable Character: 5Str [2] Is Printable Character: Str [3] Is Printable Character: @str [4] IS Printable Character :;

Isspace (whether the test character is a space character)

related functions

ISGRAPH

Header file

#include

Definition function

INT ISSPACE (INT C)

Function description

Check if the parameter c is a space character, that is, it is to determine whether it is a space (''), positioning characters ('/ t'), CR ('/ R'), wrap ('/ n'), vertical positioning characters ('/ V ') or turn the page (' / f ').

return value

Returns true if the parameter C is a space character, otherwise returns NULL (0).

Additional information

This is a macro definition, a non-real function.

example

/ * Find a space character contained in the string Str [] and display the space character of the space character * / # clude main () {char str = "123c @ # fd / tsp [e? / N "; int I; for (i = 0; STR [I]! = 0; I ) IF (Isspace (STR [I])) Printf (" Str [% D] is a white-space character:% D / N ", I, STR [I]);}

Str [4] is a white-space Character: 32STR [7] is a white-space Character: 32Str [10] is a white-space character: 9 / * / t * / str [16] is a white-space Character : 10 / * / t * /

ISPUNCT (testing characters are punctuation or special symbol)

related functions

Isspace, isdigit, isalpha

Header file

#inlude

Definition function

INT ISPUNCT (INT C)

Function description

Check if the parameter c is a punctuation or special symbol. Returns True is also the representative parameter C is non-spaced, non-digital and non-English letters.

return value

v If the parameter C is the punctuation or special symbol, return TRUE, otherwise return null (0).

Additional information

This is a macro definition, a non-real function.

example

/ * List the punctuation or special symbols in the string STR * / # include main () {char str [] = "123c @ #fdsp [e?"; Int 1; for (i = 0 ; STR [I]! = 0; i ) IF (ISPUNCT (STR [I])) Printf ("% C / N", STR [I]);}

carried out

v @ # [?

iSupper (testing characters is uppercase English letters)

related functions

Isalpha, Islower

Header file

#include

Definition function

Int Isupper (int C)

Function description

Check if the parameter c is uppercase English letters.

return value

If the parameter C is uppercase English letters, returns true, otherwise returns NULL (0).

Additional information

This is a macro definition, a non-real function.

example

/ * Find a string STR in the character * / # include main () {char str [= "123c @ # fdsp [e?"; Int 1; for (i = 0) ; STR [I]! = 0; i ) IF (isupper (STR [I])) Printf ("% C Is An Uppercase Character / N", STR [I]);}

carried out

F is an uppercase charactercterd is an uppercase characterp is an uppercase charactercase character

Isxdigit (test character is 16 credit)

related functions

Isalnum, isdigit

Header file

#include

Definition function

INT Isxdigit (INT C)

Function description

Check if the parameter C is a 16-en-numeric number, as long as c is one of the following cases, returns true. Binary number: 0123456789Abcdef.

return value

If the parameter C is a 16-encycloped number, returns true, otherwise NULL (0) is returned.

Additional information

This is a macro definition, a non-real function.

example

/ * Find the character string STR in the character * / # include main () {char str [] = "123c @ # fdsp [e?"; Int i; for (i = 0; STR [i]! = 0; i ) IF (isxdigit (STR [I])) Printf ("% C Is A Hexadecimal Digits / N", STR [I]);}

1 IS A Hexadecimal Digits2 IS A HEXADECIMAL DIGITS3 IS A HEXADECIMAL DIGITSC IS A HEXADECIMAL DIGITSD IS A HEXADECIMAL DIGITSD IS A HEXADECIMAL DIGITSE IS A HEXADECIMAL DIGITS

ATOF (convert a string into floating point model)

related functions

ATOI, Atol, Strtod, Strtol, Strtoul

Header file

#include

Definition function

Double ATOF (const char * nptr);

Function description

ATOF () will scan the parameter nptr string, skip the front space characters, until the number or positive and negative symbols begin to do conversion, and then encounter the end of the non-digital or string ('/ 0') to end the conversion And return the results. The parameter nptr string can include a positive and negative number, decimal point, or E (E) to represent an index portion, such as 123.456 or 123E-2.

return value

Returns the converted floating point type.

Additional information

ATOF () is the same as the result of using Strtod (NPTR, (Char **) NULL).

example

/ * Transition the string A with the string B after adding * / # include main () {char * a = "- 100.23"; char * b = "200e-2"; float c ; C = ATOF (a) atof (b); Printf ("c =%. 2F / n", c);}

carried out

C = -98.23

ATOI (convert a string into an integer)

related functions

ATOF, Atol, Atrtod, Strtol, Strtoul

Header file

#include

Definition function

INT ATOI (const char * nptr);

Function description

Atoi () will scan the parameter nptr string, skip the front space character, until the number or positive and negative symbols begin to do conversion, and then encounter the end of the non-digital or string ('/ 0') to end the conversion And return the results.

return value

Returns the constant number after the conversion.

Additional information

ATOI () with the use of Strtol (NPTR, (Char **) NULL, 10); the result is the same.

example

/ * Convert the string A and the string B to the digital after adding * / # include mian () {char a [] = "- 100"; char b [] = "456"; int C ; C = ATOI (a) atoi (b); Printf (C =% D / N ", C);

carried out

C = 356

ATOL (convert a string string to growth)

related functions

ATOF, Atoi, Strtod, Strtol, Strtoul

Header file

#include

Definition function

Long atol (const char * nptr);

Function description

Atol () will scan the parameter nptr string, skip the front space characters, until the number or positive and negative symbols begin to do transformation, and then encounter non-digital or strings ('/ 0') to end the conversion And return the results. return value

Returns the conversion of long-intensive numbers.

Additional information

Atol () with the use of Strtol (nptr, (char **) NULL, 10); the result is the same.

example

/ * Convert the string A with the string B to the digital after adding * / # include main () {char a [] = "1000000000"; char b [] = "234567890"; long C; C = atol (a) atol (b); Printf ("C =% D / N", C);

carried out

C = 1234567890

GCVT (convert the floating point type into a string, take a four round)

related functions

ECVT, FCVT, SPRINTF

Header file

#include

Definition function

Char * GCVT (double number, size_t ndigits, char * buf);

Function description

GCVT () is used to convert the parameter Number to the ASCII code string, and the parameter ndigits represent the number of bits displayed. GCVT () and ECVT () and FCVT () Different parts of the gcvt () The string after conversion contains a decimal point or a positive and negative symbol. If the conversion is successful, the converted string will place the space referred to in the parameter buf pointer.

return value

Returns a string pointer, this address is the buf pointer.

Additional information

example

#include main () {double a = 123.45; double b = -1234.56; char * ptr; int decpt, sign; GCVT (A, 5, PTR); Printf ("a value =% S / N ", PTR); PTR = GCVT (B, 6, PTR); Printf (" B Value =% S / N ", PTR);}

carried out

a value = 123.45b value = -1234.56

Strtod (convert a string into floating point)

related functions

ATOI, Atol, Strtod, Strtol, Strtoul

Header file

#include

Definition function

Double Strtod (const char * nptr, char ** endptr);

Function description

Strtod () will scan the parameter nptr string, skip the front space character, until the number or positive and negative symbols begin to do conversion, to end the conversion at the end of the non-numeric or string ('/ 0'), and Return the result. If Endptr is not NULL, the character pointer in NPTR to be terminated by a non-conditional condition is back by ENDPTR. The parameter nptr string can contain a positive and negative number, decimal point, or E (E) to represent an index portion. Such as 123.456 or 123E-2.

return value

Returns the converted floating point type.

Additional information

Refer to ATOF ().

example

/ * Use 10, 2, 16, respectively, 10, 2, 16, and C, to digital * / # include mian () {char a [] = "1000000000"; char b [] = " 1000000000 "; Char C [] =" fff "; Printf (" A =% D / N ", StrtOD (A, NULL, 10)); Printf (" B =% D / N ", Strtod (B, Null, 2)); Printf ("C =% D / N", StrtOD (C, NULL, 16));}

A = 1000000000B = 512c = 65535

STRTOL (convert a string string to growth)

related functions

ATOF, Atoi, Atol, Strtod, Strtoul

Header file

#include

Definition function

Long Int Strtol (const char * nptr, char ** endptr, int base);

Function description

Strtol () will convert the parameter nptr string according to the parameter base. Parameter base ranges from 2 to 36, or 0. Parameter base represents the enveloped method, such as 10, 10 encompasses, if the base value is 16, and 16 is used. When the Base value is 0, it is a 10-way conversion, but if the '0x' preamplifier will use 16 credit transformation. First start Strtol () will scan the parameter nptr string, skip the front space characters until you encounter a digital or positive and negative symbol, and then encounter the end of the non-digital or string ('/ 0') end conversion. And return the results. If the parameter endptr is not NULL, the character pointer in the NPTR that is not terminated is returned by ENDPTR.

return value

Returns the long-elected long-intensive number after the conversion, otherwise returns ERANGE and stores the error code into errno.

Additional information

ERANGE The specified conversion string exceeds the legal scope.

example

/ * Take strings A, B, and C to use 10, 2, 16, respectively, converted into numbers * / # include main () {char a [] = "1000000000"; char b [] = " 1000000000 "; CHAR C [] =" fff "; Printf (" A =% D / N ", Strtol (A, NULL, 10)); Printf (" B =% D / N ", Strtol (B, Null, 2)); Printf ("C =% D / N", Strtol (C, NULL, 16));}

carried out

A = 1000000000B = 512c = 65535

Strtoul (convert a string into an unsigned long)

related functions

ATOF, ATOI, ATOL, STRTOD, STRTOL

Header file

#include

Definition function

Unsigned long int foc (const char * nptr, char ** endptr, int base);

Function description

Strtoul converts the parameter nptr string to the parameter base to convert into a symbolic long-intensity number. Parameter base ranges from 2 to 36, or 0. The parameter base represents the adopted approach, such as 10, using 10, if the base value is 16, using a 16-carry number, etc. When the Base value is 0, it is a 10-way conversion, but if the '0x' preamplifier will use 16 credit transformation. First start Strtoul () will scan the parameter nptr string, skip the front space string until you encounter a number or positive and negative symbol to do the conversion, then encounter the end of the non-digital or string ('/ 0') Conversion and return the results. If the parameter endptr is not NULL, the character pointer in the NPTR that is not terminated is returned by ENDPTR. return value

Returns the long-elected long-intensive number after the conversion, otherwise returns ERANGE and stores the error code into errno.

Additional information

ERANGE The specified conversion string exceeds the legal scope.

example

Reference strtol ()

TOASCII (convert an integer to legitimate ASCII code characters)

related functions

Isascii, Toupper, TOLOWER

Header file

#include

Definition function

Int toascii (INT C)

Function description

TOASCII () converts the parameter C into a 7-bit Unsigned char value, and the eighth bit will be cleared, this character will be transferred to the ASCII code character.

return value

Returns the converted ASCII code character value.

example

#include main () {int a = 217; char b; Printf ("Before toascii (): a value =% d (% C) / N", A, a); b = toascii (a ); Printf ("After toascii (): a value =% D (% C) / N", B, b);}

carried out

Before toascial (): a value = 217 () after toascii (): a value = 89 (y)

TOLOWER (convert uppercase letters into lowercase letters)

related functions

Isalpha, TouPper

Header file

#include

Definition function

Int TOLOWER (INT C);

Function description

If the parameter C is uppercase letters, the corresponding lowercase letters are returned.

return value

Returns the converted lowercase letters, if you don't have to conversion, return the parameter C value.

Additional information

example

/ * Convert the uppercase letters in the S-character string into lowercase letters * / # include main () {char s [] = "Abcdefgh12345;! # $"; Int i; printf ("Before toLower () :% S / N ", S); for (i = 0; i

carried out

Before tolower (): abcdefgh12345;! # $ after tolower (): abcdefgh12345;! # $

TouPper (convert lowercase letters into uppercase letters)

related functions

Isalpha, Toolower

Header file

#include

Definition function

INT Toupper (int C);

Function description

If the parameter C is lowercase letters, the designed uppercase letter is returned.

return value

Returns the converted uppercase letters, if you do not need to be converted, return the parameter C value.

Additional information

example

/ * Convert the lowercase letters in the S-character string into uppercase letters * / # include main () {char s [] = "Abcdefgh12345;! # $"; Int i; printf ("Before Toupper () :% S / N ", S); for (i = 0; i

Before topper (): abcdefgh12345;! # $ after topper (): abcdefgh12345;! # $

Calloc (Configuring Memory Space)

related functions

Malloc, Free, Realloc, BRK

Header file

#include

Definition function

Void * Calloc (size_t nmemb, size_t size);

Function description

Calloc () is used to configure NMEMB adjacent memory units, each unit size is size, and returns a pointer to the first element. This is the same as the following way: Malloc (NMEMB * Size); however, the memory content is initialized to 0 when using the calloc () configuration memory.

return value

If the configuration is successful, a pointer is returned, and NULL is returned.

example

/ * Dynamically configured 10 Struct Test Space * / # include struct test {Int a [10]; char b [20];} main () {struct test * ptr = Calloc (SIZEOF (Struct Test) , 10);

Free (release the original memory)

related functions

Malloc, Calloc, Realloc, BRK

Header file

#include

Definition function

Void Free (Void * PTR);

Function description

The parameter PTR is a memory pointer that points to the previously being returned by Malloc (), Calloc () or Realloc (). The memory space referred to after calling free () will be recovered. If the memory space referred to by the parameter PTR has been recovered or an unknown memory address, the free () may have an expected situation. If the parameter PTR is NULL, Free () does not have any effect.

getPageSize (get a memory paging size)

related functions

SBRK

Header file

#include

Definition function

SIZE_T GETPAGESIZE (VOID);

Function description

Returns the size of a page, the unit is byte (Byte). This is the system's page size, not necessarily the same as the hardware paging.

return value

Memory page size. Additional instructions should be 4096bytes on Intel X86.

example

#include main () {printf ("page size =% d / n", getpagesize ());}

Malloc (Configuring Memory Space)

related functions

Calloc, Free, Realloc, BRK

Header file

#include

Definition function

Void * malloc (size_t size);

Function description

Malloc () is used to configure memory space, and its size is determined by the specified Size.

return value

If the configuration is successful, a pointer is returned, and NULL is returned.

example

Void P = Malloc (1024); / * Configure 1K memory * /

MMAP (establish memory map)

related functions

Munmap, Open

Header file

#include #include

Definition function

Void * mmap (void * start, size_t length, int prot, int flags, int fd, off_t offsize);

Function description

MMAP () is used to map a file content to memory, and access to the memory area is read or written directly to the content of the file. The parameter start pointing to the corresponding memory start address, typically set to NULL, the representative allows the system to automatically select the address, and the address will return after success. The parameter Length represents how much part of the file corresponds to memory.

parameter

PROT Represents Mapping Region Protection Methods The following combined prot_exec mapping area can be executed a prot_write mapping area to be written to the prot_none mapping area cannot be accessed

parameter

Flags will affect the various features of the map area. This flag is usually not encouraged. Map_shared's write data for the map area will copy back to the file and allow other maps that map the file. MAP_PRIVATE The write operation of the mapping area generates a mapping file copy, that is, any modification of private "Copy ON WRITE) does not write back to the original file content. Map_anonymous build anonymous mapping. The parameter FD is ignored at this time, and the file is not involved, and the mapping area cannot be shared with other processes. MAP_DENYWRITE only allows write operations to the mapped area, and other operations directly written directly to files will be rejected. Map_locked locks the map area, which means that the area will not be replaced (SWAP). Map_shared or map_private must be specified when you call MMAP (). The parameter fd is Open () returned file descriptor, which represents the file to be mapped to memory. Parameter OFFSET is the offset of the file mapping, usually set to 0, and the representative corresponding to the front of the file, the OFFSET must be an integer multiple of the page size.

return value

If the mapping is successful, the memory start address of the map area is returned, otherwise returns Map_failed (-1), and the error is existed in Errno.

error code

Ebadf parameter fd is not a valid file description word EACCES access is incorrect. If the file must be readable in the case of map_private, use map_shared to have Prot_Write and the file to be written. Einval parameters Start, Length, or Offset has a illegal. The Eagain file is locked, or too many memory is locked. ENOMEM is insufficient.

example

/ * Use mmap () to read / etc / passwd file content * / # include #include #include #include # Include main () {Int fd; void * start; struct stat sb; fd = open ("/ etc / passwd", o_rdonly); / * Open / etc / passwd * / fstat (FD, & SB); / * Get file size * / start = mmap (null, sb.st_size, prot_read, map_private, fd, 0); if (start = = map_failed) / * Judgment whether mapped success * / return; printf ("% s ", start); MUNMA (START, SB.ST_SIZE); / * Release Mapping * / Closed (FD);

carried out

Root: x: 0: root: / root: / bin / bashbin: x: 1: 1: bin: / bin: daemon: x: 2: 2: daem: / sbinadm: x: 3: 4: adm: / var / adjm: lp: x: 4: 7: lp: / var / spool / lpd: sync: x: 5: 0: sync: / sbin: bin / sync: shutdown: x: 6: 0: shutdown: / sbin: SHUTDOWN: / sbin / shutdownhalt: x: 7: 0: Halt: / sbin: / sbin / haltmail: x: 8: 12: Mail: / var / spool / mail: news: x: 9: 13: News: / var / spool / news: uucp: x: 10: 14: uucp: / var / spool / uucp: Operator: x: 11: 0: Operator: / root: Games: x: 12: 100: Games: / usr / games: gopher: X: 13: 30: Gopher: / usr / lib / gopher-data: ftp: x: 14: 50: FTP User: / Home / FTP: Nobody: x: 99: 99: NoBody: /: xfs: x: 100 : 101: X Font Server: / ETC / XLL / FS: / BIN / FALSEGDM: x: 42: 42:: / HOME / GDM: / BIN / BASHKIDS: X: 500: 500: / Home / Kids: / bin / BashmunMap (release memory map)

related functions

Mmap

Header file

#include #include

Definition function

INT Munmap (Void * Start, SIZE_T LENGTH);

Function description

MunMap () is used to cancel the mapping memory of the parameter start, and the parameter length is the memory size to cancel. When the process ends or utilizes the EXEC correlation function to perform other programs, the mapping memory will be automatically released, but the mapping will not be released when the corresponding file description word is turned off.

return value

Returns 0 if the release of the mapping is successful, otherwise returns -1, the error is existed in errno Error code Einval

parameter

Start or Length is not legal.

example

Refer to MMAP ()

Asctime (expressed time and date in string format)

related functions

Time, CTIME, GMTIME, LOCALTIME

Header file

#include

Definition function

Char * asctime (const struct tm * timeptr);

Function description

Asctime () converts the information in the TM structure referred to the parameter TimePtr into the time dates represented by the real world, and then returns the result in a string form. This function has been converted into local time by the time zone, and the string format is: "WED JUN 30 21:49:08 1993 / N"

return value

This string may be destroyed if the relevant time date function is called again. This function is different from CTIME in the incoming parameters.

Additional information

Returns a string represents the current local time date.

example

#include main () {time_t timep; time (& timep); Printf ("% s", asctime (gmtime (& time)));}

carried out

Sat Oct 28 02:10:06 2000

CTIME (expressed time and date in string format) related functions

Time, Asctime, GMTIME, LOCALTIME

Header file

#include

Definition function

Char * ctime (const time_t * Timep);

Function description

CTIME () converts the information in the Time_t structure referred to the parameter TIMEP into the time date representation method used by the real world, and then returns the result in a string form. This function has been converted into local time by the time zone, and the string format is "WED JUN 30 21: 49: 08 1993 / N". This string may be destroyed if the relevant time date function is called again.

return value

Returns a string represents the current local time date.

example

#include main () {time_t timep; time (& time); Printf ("% s", ctime (& time));}

carried out

Sat Oct 28 10: 12: 05 2000

GetTimeOfDay (get the current time)

related functions

Time, CTIME, FTIME, SETTIMEOFDAY

Header file

#include #include

Definition function

INT getTimeOfDay (Struct Timeval * TV, Struct Timezone * Tz)

Function description

GetTimeOfDay () will return the current time there is a structure referred to in TV. The information of the local time zone is placed in the structure referred to in Tz. The TimeVal structure is defined as: struct timeval {long TV_sec; / * second * / long TV_usec; ​​/ * microsecond * /}; TimeZone structure is defined as: Struct Timezone {int TZ_MINUTESWEST; / * and GREENWICH time difference * / int TZ_DSTTIME ; / * Status of daylight saving time * /}; the above two structures are defined in /usr/include/sys/time.h. The status represented by tz_dsttime is the following DST_NONE / * Do not use * / dst_usa / * United States * / DST_AUST / * AUTED * / DST_WET / * Western Europe * / DST_MET / * 中 欧 * / dst_eet / * Eastern Europe * / DST_CAN / * Canada * / DST_GB / * Great Britain * / DST_RUM / * Romania * / DST_TUR / * Turkey * / DST_Austalt / * Australia (after 1986) * /

return value

Success returns 0, the failure returns -1, the error code exists in Errno. Additional description EFAULT pointer TV and TZ are referred to by the memory space beyond access rights.

example

#include #include main () {struct timevalval TV; struct timezone tz; gettimeofday (& TV, & tz); Printf ("TV_sec;% d / n", TV, .tv_sec ); Printf ("tv_usec;% d / n", tv.tv_usec); Printf ("tz_minuteswest;% d / n", tz.tz_minuteswest); Printf ("tz_dsttime,% d / n", tz.tz_dstime); }

carried out

TV_SEC: 974857339TV_USEC: 136996TZ_MINUTESWEST: -540TZ_DSTTIME: 0

GMTIME (achieved time and date)

related functions

Time, Asctime, CTIME, LOCALTIME

Header file

#include

Definition Function StructTM * GMTIME (const time_t * Timep);

Function description

GMTIME () converts information in the Time_t structure referred to the parameter TIMEP into the time date representation method used in real world, and then returns the result by the structure Tm. The structural Tm definition is StructTM {INTTM_SEC; INTTM_MIN; int TM_HOUR; INTTM_MDAY; INTTM_MON; INTTM_YEAR; INTTM_WDAY; INTTM_YDAY; INTTM_ISDST;}; int TM_SEC represents the current number of seconds, normal range 0-59 However, it allows for 61 second INTTM_MIN to represent the current score, the number of hours counts from 0-59INT TM_HOUR, the range of 0-23int TM_MDAY is currently the number of days in the month, the range 01-31int TM_MON represents the current month, from January The number of days from 0-11int TM_Year from 1900, IntTm_wday's day, from Monday, the range is 0-6int TM_YDAY from January 1 this year, the number of days is 0- 365INT TM_ISDST Skylight Savings Time Flag This function returned to the time period without time zone conversion, but UTC time.

return value

Return structure TM represents current UTC time

example

#include main () {char * wday [] = {"Sun", "MON", "TUE", "WED", "Thu", "Fri", "SAT"}; Time_t TimeP; StructTM * P; Time (& TimeP); P = GMTIME (& TimeP); Printf ("% D% D% D", (1900 p-> tm_year), (1 P-> TM_MON), P-> TM_MDAY ); Printf ("% S% D;% D;% D / N", WDAY [P-> TM_WDAY], P-> TM_HOUR, P-> TM_MIN, P-> TM_SEC);}

carried out

2000/10/28 sat 8:15:38

LocalTime (obtained local time and date)

related functions

Time, AscTime, CTIME, GMTIME

Header file

#include

Definition function

StructTM * localtime (const time_t * timep);

Function description

LocalTime () converts the information in the Time_t structure referred to the parameter TIMEP into the time date representation method used by the real world, and then returns the result by the structure Tm. For the definition of structure TM, please refer to GMTIME (). The time dates returned by this function have been converted into local time zones.

return value

Returns the structure Tm represents the current local time.

example

#include main () {char * wday [] = {"Sun", "MON", "TUE", "WED", "Thu", "Fri", "SAT"}; Time_t TimeP; StructTM * P; Time (& TimeP); P = localtime (& TimeP); / * Get local time * / printf ("% D% D% D", (1900 p-> tm_year), (l p-> TM_MON), P-> TM_MDAY); Printf ("% S% D:% D:% D / N", WDAY [P-> TM_WDAY], P-> TM_HOUR, P-> TM_MIN, P-> TM_SEC); }

carried out

2000/10/28 sat 11:12:22

Mktime (converting the time structure data into the number of seconds) related functions

Time, Asctime, GMTIME, LOCALTIME

Header file

#include

Definition function

Time_t mktime (STRCUT TM * TIMEPTR);

Function description

MkTime () is used to convert the TM structure data referred to by parameter TimePtr into the second number of seconds that count the UTC time from 0:00 pm, January 1, 1970.

return value

Returns the number of seconds.

example

/ * Time (second) with time ()), use localtime () to convert to struct TM and then use mktine () to convert StructTM to its original second number * / # include main () {time_t Timep ; STRCUT TM * P; TIME (& TIMEP); Printf ("Time ():% D / N", TIMEP); P = LocalTime (& TimeP); TimeP = MKTIME (P); Printf ("Time () -> LocalTime () -> mktime ():% d / n ", timep);

carried out

Time (): 974943297time () -> LocalTime () -> mktime (): 974943297

SetTimeOfDay (set up time)

related functions

Time, CTIME, FTIME, GETTIMEOFDAY

Header file

#include #include

Definition function

Int setTimeOfDay (const struct timeval * tv, const struct timezone * tz);

Function description

SetTimeOfDay () will set the current time into structure information referred to by TV, and local time zone information is set to Tz. Please refer to getTimeOfDay () for a detailed description. Note that only root privileges can use this function to modify the time.

return value

Success returns 0, the failure returns -1, the error code exists in Errno.

error code

Eperm is not called setTimeOfDay (), and permissions is not enough by root permission. EINVAL time zone or a data is incorrect and cannot set the time correctly.

Time (achieved current time)

related functions

CTIME, FTIME, GETTIMEOFDAY

Header file

#include

Definition function

Time_t Time (Time_t * T);

Function description

This function returns from the UTC time from January 1, 1970, 200 minutes 0:00, 0:0:0:04. If t is not empty pointer, this function will save the return value to the memory referred to by the T pointer.

return value

Success returns the number of seconds, returns ((TIME_T) -1) value, and the error is existed in Errno.

example

#include mian () {int seconds = time ((time_t *) null); Printf ("% d / n", seconds);}

carried out

9.73e 08

BCMP (more memory content)

related functions

BCMP, STRCASECMP, STRCMP, STRCOLL, STRNCMP, STRNCASECMP

Header file

#include

Definition function

INT BCMP (Const Void * S1, Const Void * S2, INT N); Function Description

BCMP () is used to compare the front n bytes of the memory interval referred to by S1 and S2, and if the parameter N is 0, it returns 0.

return value

Returns 0 values ​​if the memory content referred to by parameters S1 and S2 is exactly the same, otherwise the non-zero value is returned.

Additional information

It is recommended to use MEMCMP ().

example

Refer to MEMCMP ().

Bcopy (copy memory content)

related functions

Memccpy, Memcpy, Memmove, STRCPY, CTRNCPY

Header file

#include

Definition function

Void Bcopy (const void * src, void * dest, int N);

Function description

Bcopy () is the same as the address used to copy the memory content referred to by SRC to DEST, but the parameter SRC and DEST are the opposite position when the function is transmitted.

return value

Additional information

It is recommended to use memcpy () replacement

example

#include main () {char desT [30] = "string (a)"; char src [30] = "string / 0String"; INT i; bcopy (src, dest, 30); / * SRC pointer placed in front * / printf (bcopy (): ") for (i = 0; I <30; i ) Printf ("% C ", DEST [I]); Memcpy (DEST SRC, 30); / * DEST pointer is placed in money * / printf ('/ nmemcpy (): "); for (i = 0; i <30; i ) Printf ("% C ", DEST [I]);

carried out

bcopy (): string stringmemcpy (): string Sring

Bzero (the content of the memory is zero)

related functions

Memset, Swab

Header file

#include

Definition function

Void Bzero (Void * S, INT N);

Function description

Bzero () will set the N bytes of the memory area referred to by the parameter S to zero. Equivalent to calling MEMSET ((Void *) S, 0, SIZE_TN);

return value

Additional information

It is recommended to use MEMSET to replace

example

Refer to MEMSET ().

Index (Find the first specified character appearing in the string)

related functions

RINDEX, SRECHR, STRRCHR

Header file

#include

Definition function

CHAR * INDEX (const char * s, int C);

Function description

Index () is used to find the first parameter C address in the parameter S string, and then returns the address that appears in the character. String end character (null) is also considered part of the string.

return value

If you find the specified character, return the address where the character is located, otherwise it returns 0.

example

#include main () {char * s = "0123456789012345678901234567890"; char * p; p = index (s, '5'); Printf (% s / n ", p);}

carried out

5.68e 25

Memccpy (copy memory content)

related functions

BCopy, Memcpy, Memmove, Strcpy, Strncpy

Header file

#include

Definition function

Void * Memccpy (Void * Dest, Const Void * src, Int C, SIZE_T N); Function Description

Memccpy () is used to copy the N bytes of the memory content referred to by SRC to the address referred to in DEST. Different from memcpy (), Memccpy () checks if the parameter c appears when copying, and returns the next byte address of the Dest in the DEST.

return value

Returns the next byte pointer to the Dest in the DEST. The return value is 0 indicates bytes that do not have a value C in n bytes in the N bytes of the SRC.

example

#include main () {char a [] = "string [a]"; char b [] = "string (b)"; Memccpy (A, B, 'B', SIZEOF (B)) ; Printf ("Memccpy ():% S / N", A);}

carried out

Memccpy (): String (b)

Memchr (find a specific character in a memory range)

related functions

INDEX, RINDEX, STRCHR, STRPBRK, STRRCHR, STRSEP, STRSPN, STRSTR

Header file

#include

Definition function

Void * Memchr (const void * s, int C, size_t n);

Function description

Memchr () From the header starting n bytes before the memory content refers to S, until the first value is the byte of C, the pointer to the byte is returned.

return value

If you find the specified byte, return the pointer of the byte, otherwise it returns 0.

example

#include main () {char * s = "0123456789012345678901234567890"; char * p; p = MEMCHR (S, '5', 10); Printf ("% s / n", p);}

carried out

5.68e 25

Memcmp (Compare Solid Content)

related functions

BCMP, STRCASECMP, STRCMP, STRCOLL, STRNCMP, STRNCASECMP

Header file

#include

Definition function

INT MEMCMP (Const Void * S1, Const Void * S2, SIZE_T N);

Function description

MEMCMP () is used to compare N characters before the memory interval referred to by S1 and S2. The comparison of string sizes is determined by the order on the ASCII code table, and the second order is also the value of characters. Memcmp () first subtracts the first character value of S1 to the value of the first character. If the difference is 0, continue to compare the next character, if the difference is not 0, return the difference. For example, strings "ac" and "ba" comparisons return the differences of characters 'A' (65) and 'B' (98) (-33).

return value

Returns 0 values ​​if the memory content referred to by parameters S1 and S2 is exactly the same. If S1 is greater than S2, it returns a value greater than 0. If S1 is smaller than S2, it returns a value of less than 0.

example

#include main () {char * a = "abcdef"; char * b = "abcdef"; char * c = "aacdef"; char * d = "abcdef"; printf ("Memcmp (" MEMCMP (A, B):% D / N ", MEMCMP (Void *) A, (Void *) B, 6)); Printf (" Memcmp (A, C):% D / N ", MEMCMP ((void *) a (void *) C, 6)); Printf ("" MEMCMP (A, D):% D / N ", MEMCMP ((void *) a, (void *) D, 6)); execution

Memcmp (A, B): 1 / * String A> String B, return 1 * / MEMCMP (A, C): - 1 / * String a

Memcpy (copy memory content)

related functions

Bcopy, Memcpy, Memcpy, Memmove, Strcpy, Strncpy

Header file

#include

Definition function

Void * Memcpy (Void * DEST, Const Void * src, size_t n);

Function description

Memcpy () used to copy the N bytes of the memory content referred to by SRC to the memory address referred to in DEST. Unlike struct (), memcpy () will complete the n bytes, and will not end because of the end '/ 0' encountered.

return value

Returns a pointer to the DEST.

Additional information

The memory area referred to by the pointer SRC and DEST cannot overlap.

example

#include main () {char a [30] = "string (a)"; char b [30] = "string / 0String"; INT I; STRCPY (A, B); Printf ("strcpy (): "); for (i = 0; i <30; i ) Printf ("% c ", a [i]); Memcpy (A, B, 30); Printf (" / nmemcpy (): ") For (i = 0; i <30; i ) Printf ("% c", a [i]);}

carried out

STRCPY (): String a) Memcpy (): String String

MEMMOVE (copy memory content)

related functions

Bcopy, Memcpy, Memcpy, Strcpy, Strncpy

Header file

#include

Definition function

Void * Memmove (Void * Dest, Const Void * SRC, SIZE_T N);

Function description

Memmove () is the address used to copy the memory content referred to by the memory content referred to in the SRC to DEST. Different, when the memory area referred to by SRC and DEST overlap, Memmove () can still process correctly, but the execution efficiency is slightly slower than using memcpy ().

return value

Returns a pointer to the DEST.

Additional information

The memory area referred to by the pointer SRC and DEST can overlap.

example

Refer to Memcpy ().

MEMSET (filled in a certain value)

related functions

Bzero, Swab

Header file

#include

Definition function

Void * MEMSET (Void * S, INT C, SIZE_T N); function description

MEMSET () The first n bytes referred to in the parameter S are filled in parameter c, and then return to the pointer to S. When writing a program, if you need to initialize a number of groups, MemSet () will be quite convenient.

return value

Returns a pointer to S.

Additional information

Although the parameter c is declared as int, but must be unsigned char, which ranges from 0 to 255.

example

#include main () {char s [30]; MEMSET (S, 'A', SIZEOF (S)); S [30] = '/ 0'; Printf ("% S / N", S);

carried out

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

RINDEX (Find the last specified character that appears in the string)

related functions

Index, Memchr, StrChr, STRCHR

Header file

#include

Definition function

Char * rindex (const char * s, int C);

Function description

RINDEX () is used to find the parameter C address that appears in the parameter S string, and then returns the address that appears in the character. String end character (null) is also considered part of the string.

return value

If you find the specified character, return the address where the character is located, otherwise it returns 0.

example

#include mian () {char * s = "0123456789012345678901234567890"; char * p; p = rindex (s, '5'); Printf ("% s / n", p);}

carried out

567890

STRCASECMP (ignore case comparison strings)

related functions

BCMP, MEMCMP, STRCMP, STRCOLL, STRNCMP

Header file

#include

Definition function

INT STRCASECMP (const char * s1, const char * s2);

Function description

StrCaseCMP () is used to compare parameters S1 and S2 strings, which will automatically ignore differences in cases.

return value

Returns 0 if the parameters S1 and S2 strings are the same. The S1 length is greater than S2 length returns a value greater than 0, and the S1 length returns a value of less than 0 if it is less than S2 length.

example

#include main () {char * a = "abcDef"; char * b = "abcdef"; if (! STRCASECMP (A, B)) Printf ("% s =% s / n", A , b);}

carried out

Abcdef = abcdef

STRCAT (connected two strings)

related functions

Bcopy, Memcpy, Memcpy, Strcpy, Strncpy

Header file

#include

Definition function

Char * STRCAT (CHAR * DEST, Const Char * src);

Function description

STRCAT () copy the parameter src string to the string tail of the parameter DEST. The first parameter DEST must have enough space to accommodate the string to be copied.

return value

Returns the string start address of the parameter DEST

example

#include main () {char a [30] = "string (1)"; char b [] = "string (2)"; printf ("Before strcat ():% s / n" , a); Printf ("" After strcat ():% s / n ", strcat (a, b));}

Before strat (): string (1) after strcat (): String (1) String (2)

STRCHR (Find the first specified character in the string)

related functions

INDEX, MEMCHR, RINEX, STRBRK, STRSEP, STRSPN, STRSTR, STRTOK

Header file

#include

Definition function

CHAR * STRCHR (const char * s, int C);

Function description

Strchr () is used to find the first parameter C address in the parameter S string, and then returns the address that appears in the character.

return value

If you find the specified character, return the address where the character is located, otherwise it returns 0.

example

#include main () {char * s = 0123456789012345678901234567890 "; char * p; p = strChr (s, '5'); Printf ("% s / n ", p);}

carried out

5.68e 25

STRCMP (comparison string)

related functions

BCMP, MEMCMP, STRCASECMP, STRNCASECMP, STRCOLL

Header file

#include

Definition function

INT STRCMP (const char * s1, const char * s2);

Function description

StrCMP () is used to compare parameters S1 and S2 strings. The comparison of string sizes is determined in the order on the ASCII code table, which is also the value of characters. STRCMP () first subtracts S1 first character value to S2 first character value, if the difference is 0, continue to compare the next character, if the difference is not 0, return the difference. For example, strings "AC" and "ba" comparisons return the differences in characters "a" (65) and 'B' (98) (-33).

return value

Returns 0 if the parameters S1 and S2 strings are the same. If S1 is greater than S2, it returns a value greater than 0. If S1 is smaller than S2, it returns a value of less than 0.

example

#include main () {char * a = "abcdef"; char * b = "abcdef"; char * c = "aacdef"; char * d = "abcdef"; printf ("strcmp (A, B):% D / N ", STRCMP (A, B)); Printf (" STRCMP (A, C):% D / N ", STRCMP (A, C)); Printf (" strcmp (A, D) :% D / N ", STRCMP (A, D));

carried out

STRCMP (A, B): 32STRCMP (A, C): -31Strcmp (A, D): 0

Strcoll (using the character arrangement of the current zone to compare strings)

related functions

Strcmp, BCMP, MEMCMP, STRCASECMP, STRNCASECMP

Header file

#include

Definition function

INT STRCOLL (Const Char * S1, Const Char * S2); Function Description

Strcoll () will compare S1 and S2 strings based on the text arrangements specified by the environment variable LC_Collate.

return value

Returns 0 if the parameters S1 and S2 strings are the same. If S1 is greater than S2, it returns a value greater than 0. If S1 is smaller than S2, it returns a value of less than 0.

Additional information

If lc_collate is "POSIX" or "C", strcoll () is identical to strCMP ().

example

Refer to strcmp ().

STRCPY (copy string)

related functions

Bcopy, Memcpy, Memcpy, Memmove

Header file

#include

Definition function

Char * STRCPY (Char * DEST, Const Char * src);

Function description

STRCPY () copies the parameter src string to the address referred to in the parameter DEST.

return value

Returns the string start address of the parameter DEST.

Additional information

If the memory space referred to by the parameter DEST is not large enough, it may cause a buffer overflow error, please pay special attention when writing a program, or use strNCPY () to replace it.

example

#include main () {char a [30] = "string (1)"; char b [] = "string (2)"; Printf ("Before Strcpy ():% S / N", a); Printf ("" after struffpy ():% s / n ", strcpy (a, b));}

carried out

Before structure (): String (1) after strcpy (): String (2)

STRCSPN (Returns the number of characters that continuously without specified strings in the string)

related functions

strspn

Header file

#included

Definition function

SIZE_T STRCSPN (Const Char * S, Const Char * Reject);

Function description

STRCSPN () calculates a continuous character from the beginning of the parameter S string, and these characters are not in the string referred to in the parameter reject. Simply put, if the value returned by STRCSPN () is n, the representative string S starts the n characters without N characters without string REJECT.

return value

Returns the number of characters in the string S at the beginning of the string REJECT.

example

#include main () {char * str = "Linux Was First Developed for 386/486-based PCS."; Printf ("% D / N", STRCSPN (STR, ")); Printf "% d / n", strcspn (STR, "/ -")); Printf ("% d / n", strcspn (STR, "1234567890");}

carried out

5 / * only calculate "" "," LINUX "is returned * / 33 / * calculates" / "or" - ", so the length of" 6 "is returned * / 30 / * calculates to appear So the numeric character, so returns "3" before the length of the appearance * /

STRDUP (copy string)

related functions

Calloc, Malloc, Realloc, FREE

Header file

#include

Definition function

CHAR * STRDUP (const char * s);

Function description

Strdup () will first configure the same space size as the parameter S string, then copy the contents of the parameter S string to the memory address, and then returns the address. This address can finally use free () to be released. return value

Returns a string pointer that points to the new string address after replication. If NULL returns NULL, it is insufficient.

example

#include main () {char a [] = "strdup"; char * b; b = strDUp (a); printf ("b [] = /"% s / "/ n", b) }

carried out

b [] = "strdup"

Strlen (Returns the length of the string)

related functions

Header file

#include

Definition function

SIZE_T STRLEN (Const Char * S);

Function description

Strlen () is used to calculate the length of the specified string S, not including end character "/ 0".

return value

Returns the number of characters of string s.

example

/ * String Str's length * / # include main () {char * STR = "12345678"; Printf ("str length =% d / n", strlen (STR));}

carried out

Str Length = 8

STRNCASECMP (ignore case comparison strings)

related functions

BCMP, MEMCMP, STRCMP, STRCOLL, STRNCMP

Header file

#include

Definition function

INT STRNCASECMP (Const Char * S1, Const Char * S2, SIZE_T N);

Function description

StrncaseCMP () is used to compare the N characters before the parameters S1 and S2 strings, and the difference is automatically ignored when compared.

return value

Returns 0 if the parameters S1 and S2 strings are the same. If S1 is larger than S2, it returns a value greater than 0, and S1 returns a value of less than 0 if it is smaller than S2.

example

#include main () {char * a = "abcDef"; char * b = "abcdef"; if (!! StrncaseCMP (A, B)) Printf ("% s =% s / n", A , b);}

carried out

Abcdef = abcdef

STRNCAT (connected two strings)

related functions

Bcopy, Memccpy, MeMecpy, Strcpy, Strncpy

Header file

#inclue

Definition function

Char * Strncat (Char * DEST, Const Char * src, size_t n);

Function description

STRNCAT () copy the parameter src string to n characters to the string of the character referred to as the parameter DEST. The first parameter DEST must have enough space to accommodate the string to be copied.

return value

Returns the string start address of the parameter DEST.

example

#include main () {char a [30] = "string (1)"; char b [] = "string (2)"; printf ("Before strnact ():% s / n", a); Printf ("After Strncat ():% S / N", STRNCAT (A, B, 6));

carried out

Before strnact (): String (1) after strncat (): String (1) String

STRNCPY (copy string) related functions

Bcopy, Memccpy, Memcpy, Memmove

Header file

#include

Definition function

Char * STRNCPY (Char * DEST, Const Char * src, size_t n);

Function description

Strncpy () will copy the parameter src string before n characters to the address referred to by the parameter DEST.

return value

Returns the string start address of the parameter DEST.

example

#inclue main () {char a [30] = "string (1)"; char b [] = "string (2)"; Printf ("Before Strncpy ():% s / n", a); Printf ("After Strncpy ():% S / N", STRNCPY (A, B, 6));

carried out

Before strncpy (): string (1) after strncpy (): String (1)

StrPBRK (Find the first specified character in the string)

related functions

INDEX, MEMCHR, RINDEX, STRPBRK, STRSEP, STRSPN, STRSTR, STRTOK

Header file

#include

Definition function

Char * Strpbrk (const char * s, const char * accept);

Function description

Strpbrk () is used to find any of the characters in the parameter accept string in the parameter S string.

return value

If you find the specified character, return the address where the character is located, otherwise it returns 0.

example

#include main () {char * s = "0123456789012345678901234567890"; char * p; p = strpbrk (s, "a1 839"); / * 1 will find * / printf in the s string ("% S / N", P); P = STRPRK (S, "4398"); / * 3 will first find * / printf ("% s / n", p) in the s string;

carried out

1.23e 29

Strrchr (Find the final specified character in the string)

related functions

INDEX, MEMCHR, RINDEX, STRPBRK, STRSEP, STRSPN, STRSTR, STRTOK

Header file

#include

Definition function

Char * STRRCHR (const char * s, int C);

Function description

Strrchr () is used to find the parameter C address that appears in the parameter S string, and then returns the address that appears in the character.

return value

If you find the specified character, return the address where the character is located, otherwise it returns 0.

example

#include main () {char * s = "0123456789012345678901234567890"; char * p; p = Strrchr (S, '5'); Printf ("% s / n", p);}

carried out

567890

STRSPN (Returns the number of characters that continuously without the specified string content)

related functions

STRCSPN, STRCHR, STRPBRK, STRSEP, STRSTR

Header file

#include Definition function

SIZE_T STRSPN (Const Char * S, Const Char * ACCEPT);

Function description

StRSPN () calculates a continuous character from the beginning of the parameter S string, and these characters are all characterized by ACCEPT nature. Simply, if the value returned by STRSPN () is n, the representative string S starts continuous n characters in the character string accept.

return value

Returns the string S head continuously contains the number of characters within the string accept.

example

#include main () {char * str = "Linux was first developed for 386/486-based PCs."; char * t1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; printf ( "% d / n", strspn (str , t1));

carried out

5 / * Calculate the case. Does not include "", so returns the length of Linux. * /

STRSTR (lookup specified strings in a string)

related functions

INDEX, MEMCHR, RINDEX, STRCHR, STRPBRK, STRSEP, STRSPN, STRTOK

Header file

#include

Definition function

Char * strsTR (const char * nesedle);

Function description

Strstr () Stroke NEEDLE from the string HayStack and returns the first appearance address.

return value

Returns the address of the first appearance of the specified string, otherwise returns 0.

example

#include main () {char * s = "012345678901234567890123456789"; char * p; p = strstr (s, "901"); Printf ("% s / n", p);}

carried out

9.01e 21

STRTOK (split string)

related functions

INDEX, MEMCHR, RINDEX, STRPBRK, STRSEP, STRSPN, STRSTR

Header file

#include

Definition function

Char * STRTOK (Char * S, Const Char * Delim);

Function description

STRTOK () is used to split strings into a fragment. Parameter s points to the string to which you want to divide, the parameter DELIM is a split string, and the character is changed to / 0 characters when Strtok () is found in the string of parameter s. When the first call is called, Strtok () must give the parameter S string, and the next call sets the parameter S to NULL. Each time the call is successful, it returns the next divided string pointer.

return value

Returns the next split string pointer if there is no split to return NULL.

example

#include main () {char s [] = "AB-CD: EF; GH: I-jkl; mnop; QRS-TU: VWX-Y; Z"; char * delim = "-:" CHAR * P; Printf ("% s"; startok (s, delim)); while ((p = strint (NULL, DELIM))) Printf ("% s", p); printf ("/ n") ;}carried out

AB CD EF; GH I jkl; mnop; QRS TU VWX Y; z / * -: Character has been replaced by / 0 characters * /

ABS (calculating an absolute value of integer)

related functions

Labs, FABS

Header file

#include

Definition function

Int Abs (Int J)

Function description

ABS () is used to calculate the absolute value of parameter J and then return the result.

return value

Returns the absolute value of parameter j.

example

#ingClude main () {int ansert; answer = ABS (-12); Printf ("| -12 | =% d / n", answer;

carried out

| -12 | = 12

ACOS (Refueling Strove Function)

related functions

Asin, Atan, Atan2, Cos, Sin, Tan

Header file

#include

Definition function

Double ACOS (Double X);

Function description

ACOS () is used to calculate the anti-cosrome value of the parameter X and then return the result. The parameter x ranges from -1 to 1, which will fail.

return value

Returns the calculation result between 0 to Pi, the unit is the arc, and the angle in the function library is expressed in an arc.

error code

The EDOM parameter x is out of range.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double angle; angle = acOS (0.5); Printf ("angle =% f / n", angle);}

carried out

Angle = 1.047198

Asin (take an anti-stereo function)

related functions

ACOS, Atan, Atan2, Cos, Sin, Tan

Header file

#include

Definition function

Double Asin (Double X)

Function description

asin () is used to calculate the annectal string value of the parameter X and then return the result. The parameter x ranges from -1 to 1, which will fail.

return value

Returns the calculation results between the PI / 2 of -pi / 2.

error code

EDOM parameter x beyond range

Additional information

Add -LM when compiling using GCC

example

#include main () {double angle; angle = asin (0.5); Printf ("angle =% f / n", angle);}

carried out

Angle = 0.523599

Atan (take an anlytective function value)

related functions

ACOS, ASIN, ATAN2, COS, SIN, TAN

Header file

#include

Definition function

Double Atan (double x);

Function description

Atan () is used to calculate the intermediate cut value of the parameter X and then return the result.

return value

Returns the calculation result between -pi / 2 to pi / 2.

Additional information

Add -LM when compiling using GCC

example

#include main () {double angle; angle = Atan (1); Printf ("angle =% f / n", angle);}

carried out

Angle = 1.570796

ATAN2 (get an anti-fixed function value)

related functions

ACOS, ASIN, ATAN, COS, SIN, TAN

Header file

#include

Definition function

Double Atan2 (Double Y, Double X);

Function description

ATAN2 () is used to calculate an intermediate cut value of parameter Y / X and then return the result.

return value

Returns the calculation result between -pi / 2 to pi / 2.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double angle; angle = atan2 (1, 2); Printf ("angle =% f / n", angle);}

carried out

Angle = 0.463648

CEIL (taking the minimum integer number of parameters)

related functions

Fabs

Header file

#include

Definition function

Double CEIL (Double X);

Function description

CEIL () will return the minimum integer value of not less than the parameter X, and the result is returned in the Double form.

return value

Returns the minimum integer value that is not less than the parameter X.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double value [] = {4.8, 1.12, -2.2, 0}; int i; for (i = 0; value [i]! = 0; i ) printf ("%) f =>% f / n ", value [i], ceil (value [i]));

carried out

4.800000 => 5.0000001.120000 => 2.000000-2.200000 => - 2.000000

COS (extravasive mystery)

related functions

ACOS, ASIN, Atan, Atan2, Sin, Tan

Header file

#include

Definition function

Double Cos (Double X);

Function description

COS () is used to calculate the remaining quarter value of the parameter X and then return the result.

return value

Returns the calculation result between -1 to 1.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double answer = COS (0.5); Printf ("COS (0.5) =% f / n", Answer;

carried out

COS (0.5) = 0.877583

COSH (Take Double Curve Yu Xuan Function)

related functions

Sinh, Tanh

Header file

#include

Definition function

Double Cosh (double x);

Function description

Cosh () is used to calculate the double curve of the parameter X, and then return the result. Mathematical definitions are: (Exp (X) Exp (-x)) / 2.

return value

Returns the double curve of the parameter x.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double answer = COSH (0.5); Printf ("Cosh (0.5) =% f / n", Answer;

carried out

Cosh (0.5) = 1.127626

Exp (calculation index)

related functions

Log, Log10, POW

Header file

#include

Definition function

Double Exp (Double X);

Function description

Exp () is used to calculate the X times of the end of E, that is, the EX value, and then returns the result.

return value

Returns the X of the X of E.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double answer; answer = exp (10); Printf ("E ^ 10 =% f / n", answer;}

carried out

E ^ 10 = 22026.465795

FREXP (divide the floating point number into base and index)

related functions

LDEXP, MODF

Header file

#include

Definition function

Double frexp (double x, int * eXP);

Function description

FREXP () is used to cut the floating point of the parameter x into the base and index. The base portion is returned directly, and the index portion returns to the parameter EXP pointer, multiplied the return value by the value of the EXP is the value of X.

return value

Returns the base portion of the parameter X, the index portion exists in the address referred to in the EXP pointer.

Additional information

Add -LM when compiling using GCC.

example

#include main () {int exp; double frame fraction; fraction = frexp (1024, & exp); Printf ("exp =% D / N", Exp); Printf ("fraction =% f / n" , FRAction);

carried out

Exp = 11fraction = 0.500000 / * 0.5 * (2 ^ 11) = 1024 * /

LDEXP (calculating 2 of the secondary value)

related functions

FREXP

Header file

#include

Definition function

Double LDEXP (Double X, INT Exp);

Function description

LDEXP () is used to multiply the EXP subordinate value of the parameter X, ie x * 2exp.

return value

Returns the calculation result.

Additional information

Add -LM when compiling using GCC.

example:

/ * Calculate 3 * (2 ^ 2) = 12 * / # include main () {int exp; double x, answer; answer = ldexp (3, 2); Printf ("3 * 2 ^) 2) =% F / N ", Answer;}

carried out

3 * 2 ^ (2) = 12.000000

LOG (calculating the log of E is the right value)

related functions

Exp, Log10, POW

Header file

#include

Definition function

Double log (double x);

Function description

LOG () is used to calculate the X log value at E is the bottom, and then returns the result.

return value

Returns the natural log of parameter x.

error code

The EDOM parameter x is negative, ERANGE parameter X is zero value, and zero payment is not defined.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double answer; answer = log (100); Printf ("LOG (100) =% f / n", Answer;

carried out

LOG (100) = 4.605170

LOG10 (calculating the log value at 10) related functions

Exp, Log, Pow

Header file

#include

Definition function

Double log10 (double x);

Function description

LOG10 () is used to calculate the X logs at 10 is the bottom, and then return the result.

return value

Returns the parameter x to 10% the right value.

error code

The EDOM parameter X is negative. The Range parameter X is zero value, and zero is not defined.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double answer; answer = log10 (100); printf ("log10 (100) =% f / n", answer;}

carried out

LOG10 (100) = 2.000000

POW (calculating the subordinate)

related functions

Exp, Log, Log10

Header file

#include

Definition function

Double Pow (Double X, Double Y);

Function description

Pow () is used to calculate the Y times of the base value, the XY value, and then return the result.

return value

Returns the Y secondary calculation result of the x.

error code

The EDOM parameter x is negative and the parameter Y is not an integer.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double answer; answer = POW (2, 10); Printf ("2 ^ 10 =% f / n", answer);}

carried out

2 ^ 10 = 1024.000000

Sin (Take a normal function value)

related functions

ACOS, ASIN, Atan, Atan2, Cos, Tan

Header file

#include

Definition function

Double sin (double x);

Function description

SIN () is used to calculate the positive mysterious value of the parameter X, and then return the result.

return value

Returns the calculation result between -1 to 1.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double answer = sin (0.5); Printf ("sin (0.5) =% f / n", answer;

carried out

sin (0.5) = 0.479426

SINH (Take the Dual Curve Zhengxuan Function)

related functions

Cosh, Tanh

Header file

#include

Definition function

Double Sinh (Double X);

Function description

SINH () is used to calculate the dual curve positive mysterious value of the parameter X, and then return the result. The mathematical definition is: (Exp (X) -EXP (-x)) / 2.

return value

Returns the two-curved positive mystery of the parameter x.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double answer = sinh (0.5); Printf ("SiNH (0.5) =% f / n", Answer;

carried out

Sinh (0.5) = 0.521095

SQRT (calculate square root value)

related functions

Hypotq

Header file

#include

Definition function

Double SQRT (Double X);

Function description

SQRT () is used to calculate the square root of the parameter X and then return the result. The parameter x must be a positive number.

return value

Returns the square root value of the parameter x.

error code

The EDOM parameter X is negative.

Additional information

Add -LM when compiling using GCC.

example

/ * Calculate 200 square root value * / # include main () {double root; root = sqrt (200); Printf ("Answer IS% F / N", root;}

carried out

Answer IS 14.142136

TAN (Take a fixed function value)

related functions

Atan, Atan2, Cos, Sin

Header file

#include

Definition function

Double Tan (Double X);

Function description

TAN () is used to calculate the positive cut value of the parameter X, and then return the result.

return value

Returns the positive cut value of the parameter X.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double answer = tan (0.5); Printf ("TAN (0.5) =% f / n", Answer;

carried out

Tan (0.5) = 0.546302

Tanh (Take the dual curve positive cut function)

related functions

Cosh, Sinh

Header file

#include

Definition function

Double Tanh (double x);

Function description

TANH () is used to calculate the dual curve positive cut value of the parameter X, and then return the result. The mathematical definition is: sinh (x) / cosh (x).

return value

Returns the dual curve positive cut value of the parameter x.

Additional information

Add -LM when compiling using GCC.

example

#include main () {double answer = tanh (0.5); Printf ("Tanh (0.5) =% f / n", Answer;

carried out

Tanh (0.5) = 0.462117

Endgrent (closed group file)

related functions

GetGrent, setgrent

Header file

#include #include

Definition function

Void Endgrent (Void);

Function description

Endgrent () is used to close password files opened by getGrent ().

return value

Additional information

example

Please refer to getGrent () and setgrent ().

Endpwent (Close password file)

related functions

Getpwent, setpwent

Header file

#include #include

Definition function

Void Endpwent (Void);

Function description

Endpwent () is used to close password files opened by getpwent ().

return value

Additional information

example

Please refer to getPwent () and setPwent ().

Endutent (turn off UTMP file)

related functions

Getutent, setutent

Header file

#include

Definition function

Void Endutent (Void);

Function description

Endutent () is used to close UTMP files opened by Getutent.

return value

Additional information

example

Please refer to Getutent ().

FGETGrent (read the group format from the specified file)

related functions

Fgetpwent

Header file

#include #include #include

Definition function

Struct Group * getGrent (file * stream); function description

fgetGrent () reads a row of data from the file specified by the parameter stream, then returns the data with the Group structure. The file specified by the parameter stream must be in the same format as the ETC / Group. GROUP structure definition, please refer to getGrent ().

return value

Returns Group structure data, if NULL is returned, indicating that there is no data, or an error occurs.

example

#include #include #include main () {struct group * data; file * stream; int i; stream = fopen ("/ etc / group", "r"); while ((data = fgetgrent (stream))! = 0) {i = 0; Printf ("% s:% s:% D:", Data-> gr_name, data-> gr_passwd, Data- > gr_gid); While (data-> gr_mem [i]) PRINTF ("% s,", data-> gr_mem [i ]); printf ("/ n");} fclose (stream);}

carried out

Root: x: 0: root, bin: x: 1: root, bin, daemondaemon: x: 2: root, bin, daemonsys: x: 3: root, bin, admadm: x: 4: root, adm, daemotty: x: 5disk: x: 6: rootlp: x: x: 8kmem: x: 9wheel: x: 10: rootmail: x: 12: Mailnews: x: 13: Newsuucp: x: 14: uucpman: x: 15games: x: 20gopher: x: 30dip: x: 40: ftp: x: 50nobody: x: 99:

FGetPwent (read the password format from the specified file)

related functions

FGETGRENT

Header file

#include #include #include

Definition function

Struct Passwd * fgetpwent (file * stream);

Function description

FgetPwent () reads a row of data from the file specified by the parameter stream, then returns the data with the Passwd structure. The file specified by the parameter stream must be in the same format as / etc / passwd. Please refer to getpwent (), please refer to getPwent ().

return value

Returns Passwd structure data, if NULL is returned, indicating that there is no data, or an error occurs.

example

#include #include main () {struct passwd * user; file * stream; stream = fopen ("/ etc / passwd", "r"); while ((user = FGetPwent (stream))! = 0) {Printf ("% s:% d:% D:% s:% s:% s / n", user-> pw_name, user-> pw_uid, user-> pw_gid, user -> pw_gecos, user-> pw_dir, usr-> pw_shell);}}

carried out

Root: 0: 0: root: / root: / bin / bashbin: 1: 1: bin: / bin: daemon: 2: 2: daem: / sbin: adm: 3: 4: ADM: / VAR / ADM: LP : 4: 7: lp: / var / spool / lpd: sync: 5: 0: Sync: / sbin: / bin / syncshutdown: 6: 0: Shutdown: / sbin: / sbin / shutdownhalt: 7: 0: Halt: / SBIN: / SBIN / HALTMAIL: 8: 12: Mail: / VAR / Spool / Mail: News: 9: 13: News: VAR / Spool / NewsuUcp: 10: 14: uucp: / var / spool / uucp: Operator: 11: 0: Operator: / root: Games: 12: 100: Games: / usr / games: Gopher: 13: 30: Gopher: / usr / lib / gopher-data: ftp: 14: 50: FTP User: / Home / FTP: NoBody: 99: 99: Nobody: /: xfs: 100: 101: x font server: / etc / xll / fs: / bin / falsegdm: 42: 42: / Home / GDM: / BIN / BASHKIDS: 500 : 500:: / Home / Kids: / bin / BashGetegid (achieved a valid group code)

related functions

GETGID, SETGID, SETREGID

Header file

#include #include

Definition function

GID_T GETEGID (VOID);

Function description

GetEgID () is used to obtain a valid group identification code for executing the current process. A valid group identification code is used to determine the permissions of the process execution time. Return value returns a valid grouping code.

example

Main () {Printf ("EGID IS% D / N", getGID ());

carried out

EGID IS 0 / * When using root, execute sample programs * /

GetEuid (effective user identification code)

related functions

Getuid, Setreuid, SetUID

Header file

#include #include

Definition function

Uid_t getEuid (void)

Function description

getEuid () is used to obtain a user identification code that performs current process valid. A valid user identification code is used to determine the permissions executed by the process, and thereby changing this value, the process can get additional permissions. If the SETID bit of the execution file has been set, the file is executed, the EUID value of the process is set to the UID of the file owner. For example, the permission to perform file / usr / bin / passwd is -RS - X - X, which is a setID (SUID) bit, and when any user is executing Passwd, its valid user identification code is set The UID value of the Passwd owner, that is, the root's UID value (0).

return value

Returns a valid user identification code.

example

Main () {Printf ("EUID IS% D / N", getEuid ());}

carried out

EUID IS 0 / * When using root, execute sample programs * /

getGID (get a real formation notch)

related functions

GETEGID, SETREGID, SETGID

Header file

#include #include

Definition function

GID_T getGID (Void);

Function description

getgid () is used to obtain a code not code that executes the current process.

return value

Return group identification code

example

Main () {Printf ("GID IS% D / N", getgid ());}

carried out

GID is 0 / * When using the root identity, the sample program is executed * / getGrent (obtained from the account number in the group file)

related functions

Setgrent, Endgrent

Header file

#include #include

Definition function

Struct Group * getGrent (void);

Function description

getGrent () is used to read a group data from the group file (/ etc / group), which is returned in the GROUP structure. The first group data will be obtained when the first call is called, and the next data will be returned each time until NULL is returned when there is no data. Struct group {char * GR_NAME; / * Group name * / char * GR_PASSWD; / * Group password * / gid_t gr_gid; / * 组 组 别 * / char ** GR_MEM; / * Group member account * /}

return value

Returns Group structure data, if NULL is returned, indicating that there is no data, or an error occurs.

Additional information

getGrent () opens group files during the first call, and read data () can be used after reading the data.

error code

EnomeM is insufficient and cannot be configured.

example

#include #include main () {struct group * data; int i; while ((data = getGrent ())! = 0) {i = 0; printf ("% S:% s:% D: ", DATA-> GR_NAME, DATA-> GR_PASSWD, DATA-> GR_GID); while (data-> gr_mem [i]) Printf ("% s, ", data-> gr_mem [i ]); Printf ("/ n");} endgrent ();

carried out

Root: x: 0: root, bin: x: 1: root, bin, daemon, daem: x: 2: root, bin, daemon, sys: x: 3: root, bin, adm, adm: x: 4: Root, ADM, Daemontty: x: 5disk: x: 6: rootlp: x: 7: daemon, lpmem: x: 8kmem: x: 9: Wheel: x: 10: rootmail: x: 12: Mailnews: x: 13: Newsuucp: x: 14: uucpman: x: 15: Games: x: 20gopher: x: 30dip: x: 40ftp: x: 50nobody: x: 99

Getgrgid (acquired data from the group file)

related functions

Fgetgrent, getGrent, getGRNAM

Header file

#include #include

Definition function

Strcut group * getgrgid (GID_T GID);

Function description

GETGRGID () is used to search the group file one by one by the group identification code specified by the parameter GID. When you find it, the data of the group is returned in a Group structure. GROUP structure Please refer to getGrent ().

return value

Returns Group structure data, if NULL is returned, indicating that there is no data, or an error occurs.

example

/ * Get gad = 3 group data * / # include #include main () {strcut group * data; int i = 0; data = getGRGID (3); Printf "% S:% s:% d:", data-> gr_name, data-> gr_passwd, data-> gr_gid); while (data-> gr_mem [i]) Printf ("% s,", data-> MEM [i ]); Printf ("/ n");}

Sys: x: 3: root, bin, adm

getGRNAM (acquired data from the group file)

related functions

Fgetgrent, getger, getgruid

Header file

#include #include

Definition function

Strcut Group * getGRNAM (const char * name);

Function description

getGRNAM () is used to search the parameter one by one. Then the specified group name is found, and the data of the group is returned in the group structure. GROUP structure Please refer to getGrent ().

return value

Returns Group structure data, if NULL is returned, indicating that there is no data, or an error occurs.

example

/ * Group data acquired Add data * / # incrude #include main () {strcut group * data; int i = 0; DATA = getGRNAM ("ADM"); Printf "% S:% s:% D:", DATA-> GR_NAME, DATA-> GR_PASSWD, DATA-> GR_GID); while (data-> gr_mem [i]) Printf ("% s,", data-> gr_mem [i ]); Printf ("/ n");

carried out

ADM: X: 4: root, adm, daemon

GetGroups (get a group code)

related functions

Initgroups, setGroup, getgid, setgid

Header file

#include #include

Definition function

INT getGroups (int size, gid_t list []);

Function description

getGroup () is used to achieve the group code to which the user belongs. The number of GID_Ts that can be accommodated are LIST []. If the parameter size value is zero, this function will only return the number of users belonging to the user.

return value

Returns the group identification code, returns -1 if there is an error.

error code

The efault parameter LIST array address is not legal. The EINVAL parameter size value is not enough to accommodate all groups.

example

#include #include main () {gid_t list [500]; int x, i; x = getGroups (0.list); getGroups (x, list); for (i = 0; i

carried out

0: 001: 012: 023: 034: 045: 066: 10

GetPW (get the password file data for the specified user)

related functions

Getpwent

Header file

#include #include

Definition function

INT getPW (UID_T UID, Char * BUF); function description

GetPW () will find the user account data specified by the parameter UID from the / etc / passwd, and return -1. The returned BUF string format is as follows: Account: Password: User ID (UID): Uncapacity (GID): Full Name: Root Code: shell

return value

Returning 0 means successful, returns -1 when there is an error.

Additional information

1. GetPW () will have potential security issues, please try to use other functions. 2. Use the SHADOW system to extract / etc / passwd, so the password obtained using the getPw () will be "X".

example

#include #include main () {char buffer [80]; getpw (0, buffer); Printf ("% s / n", buffer;}

carried out

Root: x: 0: 0: root: / root: / bin / bash

GetPwent (data from the password file)

related functions

Getpw, FgetPwent, Getpwnam, GetPwUID, SetPwent, Endpwent

Header file

#include #include

Definition function

STRCUT Passwd * getpwent (void);

Function description

GetPwent () is used to read a user data from the password file (/ etc / passwd), which is returned by the Passwd structure. The first user data will be taken during the first call, and then the next data will be returned once, until NULL is returned when there is no data. The Passwd structure defines the following struct passwd {char * pw_name; / * user account * / char * pw_passwd; / * user password * / uid_t pw_uid; / * user identification code * / gid_t pw_gid; / * Unconscent code * / char * pw_gecos ; / * User full name * / char * pw_dir; / ​​* Home Catalog * / char * pw_shell; / * The shell path used * /};

return value

Returns Passwd structure data, if NULL is returned, indicating that there is no data, or an error occurs.

Additional information

getpwent () The password file is opened when the first call is called. After reading the data, you can use endpwent () to close the password file. The error code enomeM is insufficient, and the Passwd structure cannot be configured.

example

#include #include main () {structure passwd * user; while ((user = getpwent ())! = 0) {Printf ("% s:% D:% D :% s:% s:% s / n ", user-> pw_name, user-> pw_uid, user-> pw_gid, user-> pw_gecos, user-> pw_dir, user-> pw_shell);} endpwent ();}

carried out

Root: 0: 0: root: / root: / bin / bashbin: 1: 1: bin: / bin: daemon: 2: 2: daem: / sbin: adm: 3: 4: ADM: / VAR / ADM: LP : 4: 7: lp: / var / spool / lpd: sync: 5: 0: Sync: / sbin: / bin / syncshutdown: 6: 0: Shutdown: / sbin: / sbin / shutdownhalt: 7: 0: Halt: / SBIN: / SBIN / HALTMAIL: 8: 12: Mail: / VAR / Spool / Mail: News: 9: 13: News: VAR / Spool / NewsuUcp: 10: 14: uucp: / var / spool / uucp: Operator: 11: 0: Operator: / root: Games: 12: 100: Games: / usr / games: Gopher: 13: 30: Gopher: / usr / lib / gopher-data: ftp: 14: 50: FTP User: / Home / FTP: NoBody: 99: 99: Nobody: /: xfs: 100: 101: x font server: / etc / xll / fs: / bin / falsegdm: 42: 42: / Home / GDM: / BIN / BASHKIDS: 500 : 500:: / home / kids: / bin / bashgetpwnam (data from the password file get the specified account)

related functions

Getpw, fgetpwent, getpwent, getpwwuid

Header file

#include #include

Definition function

Struct Passwd * getpwnam (const char * name);

Function description

GetPwnam () is used to search one by one to search the account name specified by the parameter. When it is found, the user's data is returned in the Passwd structure. Please refer to getPwent ().

return value

Returns Passwd structure data, if NULL is returned, indicating that there is no data, or an error occurs.

example

/ * Get the root account identification code and root directory * / # include #include main () {struct passwd * user; user = getpwnam ("root"); Printf (" Name:% s / n ", user-> pw_name); Printf (" UID:% D / N ", User-> PW_UID); Printf (" HOME:% S / N ", user-> pw_dir);}

carried out

Name: rootuid: 0home: / root

GetPwUID (get the specified UID in the password file)

related functions

Getpw, fgetpwent, getpwent, getpwnam

Header file

#include #include

Definition function

Struct Passwd * getPwUID (UID_T UID);

Function description

GetPWUID () is used to search the user identification code specified by the parameter UID one by one. When it is found, the data of the user is returned to the structure to return the data of the user in the PassWD structure. Please refer to getPwent ().

return value

Returns Passwd structure data, if NULL is returned, indicating that there is no data, or an error occurs.

example

#include #include main () {struct passwd * user; user = getpwUID (6); printf ("name:% s / n", user-> pw_name); Printf ("UID:% D / N", USER-> PW_UID); Printf ("HOME:% S / N", user-> pw_dir);

Name: shutdownuid: 6Home: / sbin

GetUID (get a real user identification code)

related functions

GeTEUID, Setreuid, SetUID

Header file

#include #include

Definition function

UID_T getuid (void);

Function description

GetUID () is used to obtain a user identification code for executing the current process.

return value

User identification code

example

Main () {Printf ("UID IS% D / N", getuid ());}

carried out

UID IS 0 / * When using root as an example program, * /

Getutent (get account login data from UTMP file)

related functions

Getutent, GetId, Getutline, Setutent, Endutent, Pututline, Utmpname

Header file

#include

Definition function

Struct utmp * getutent (void);

Function description

Getutent () is used to read a login data from the UTMP file (/ var / run / utmp), which is returned in the UTMP structure. The first user data will be taken during the first call, and then the next data will be returned once, until NULL is returned when there is no data. The UTMP structure defines the following struct utmp {short int ut_type; / * login type * / PID_T UT_PID; / * Login process PID * / char ut_line [ut_linesize]; / * login device name, omitted "/ dev /" * / char UT_ID [4]; / ​​* inittab id * / char ut_user [ut_namesize]; / * Login account * / char ut_host [ut_hostsize]; / * login account remote host name * / struxt exit_status ut_exit; / * When type is dead_process The end of the process * / long int ut_session; / * sessioc id * / struct timeval UT_TV; / * Time Record * / INT32_T UT_ADDR_V6 [4]; / ​​* Network address of the remote host * / char __unused [20]; / * Reserved Unused * /}; UT_TYPE has several types: Empty This is empty record. Run_LVL Record System Run-Level Change Boot_Time Record System Power On time New_TIME Record the time of the system time OLD_TINE records when changing the time of the system time. INIT_PROCESS records a process that is derived from INIT. Login_Process records the login process. User_Process records a general process. DEAD_PROCESS records a process of ending. Accounting is currently not used. EXIT_STATUS Structure Definition Struct EXIT_STATUS {Short INT E_TERMINATION; / * Process End State * / Short Int E_EXIT; / * Process Exit Status * /}; TimeVal Structure Definition Please refer to getTimeOfDay (). Related constants are as follows: UT_Linesize 32UT_NAMESIZE 32UT_HOSTSIZE 256

return value

Returns UTMP structure data, if NULL is returned, indicating that there is no data, or there is an error.

Additional information

Getutent () The UTMP file will be opened when the first call is called. After reading the data, you can use endup file to close the UTMP file.

example

#include main () {struct utmp * u; while (u = getute ())) {if (u-> ut_type = = user_process) Printf ("% D% S% S% S / N ", U-> ut_type, u-> ut_user, u-> ut_line, u-> ut_host);} endutent ();

carried out

/ * Indicates that there are three root accounts to log in / DEV / PTS / 0, / DEV / PTS / 1, / DEV / PTS / 2 * / 7 root PTS / 07 root PTS / 17 ROOT PTS / 2

GetId (find specific records from UTMP files)

related functions

Getutent, getutline

Header file

#include

Definition function

STRCUT UTMP * GETUTID (STRCUT UTMP * UT);

Function description

GetId () is used to search the parameter UT specified from the current UTMP file, if ut-> ut_type is Run_LVL, boot_time, new_time, OLD_TIME where it looks for records that match UT-> UT_TYPE; If UT-> UT_TYPE is one of INIT_PROCESS, LOGIN_PROCESS, USER_PROCESS, or DEAD_PROCESS, look for records that match UT-> UT_ID. Find the matched record returned the data in a UTMP structure. For the UTMP structure, please refer to Getutent ().

return value

Returns UTMP structure data, if NULL is returned, indicating that there is no data, or there is an error.

example

#include main () {struct utmp ut, * u; ut.ut_type = run_lvl; while (u = getId (& UT))) {printf ("% D% S% S% S / N" U-> ut_type, u-> ut_user, u-> ut_line, u-> ut_host);}}

carried out

1 RunLvel -

GetLine (find specific records from the UTMP file)

related functions

Getutent, GetId, Pututline

Header file

#include

Definition function

Struct utmp * getutline (struct utmp * UT);

Function description

GetUTLine () is used to search from UT_TYPE for user_process or login_process, and UT_LINE and UT-> UT_LINE are consistent. Find the matching record that returns the data in the UTMP structure, please refer to getutent ().

return value

Returns UTMP structure data, if NULL is returned, indicating that there is no data, or there is an error.

example

#include main () {struct utmp ut, * u; strcpy (ut.ut_line, "pts / 1"); while (u = getload (& UT))) {printf ("% D% s % S% S / N ", U-> UT_TYPE, U-> UT_USER, U-> UT_LINE, U-> UT_HOST);}}

7 root PTS / 1

InIntGroups (Initial Group List)

related functions

Setgrent, Endgrent

Header file

#include #include

Definition function

INT INITGROUPS (Const Char * User, GID_T Group);

Function description

INITGROUPS () is used to read a group data from the group file (/ etc / group). If there is a parameter user in the member of the group data, the parameter group identification code is added to this data.

return value

If the success is successful, it returns 0, and the failure returns -1, and the error code is existed in Errno.

Pututline (write UTMP record)

related functions

Getutent, getId, getutline

Header file

#include

Definition function

Void Pututline (struct utmp * UT);

Function description

Pututline () is used to record the UTMP structure of the parameter UT to the UTMP file. This function will first use getutID () to get the correct write location. If you do not find a match, you will join the UTMP file, the UTMP structure, please refer to getutent ().

return value

Additional information

Need to write / var / run / utmp

example

#include main () {struct utmp ut; ut.ut_type = user_process; ut.ut_pid = getPid (); strcpy (ut_user, "kids"); strcpy (ut.ut_line, "PTS / 1 "); Struct (ut_host," www.gnu.org "); Pututline (& UT);}

carried out

/ * Observe the instruction WHO -L observation after performing example * / root PTS / 0 DEC9 19: 20kids PTS / 1 DEC12 10:31 (www.gnu.org) root PTS / 2 DEC12 13:33

SeteUID (set a valid user identification code)

related functions

SetUID, SetReuid, SetFsuID

Header file

#include

Definition function

INT setuid (UID_T EUID);

Function description

STEUID () is used to reset the valid user identification code for performing the current process. Under Linux, STEUID (EUID) is equivalent to SetREUID (-1, EUID).

return value

If the execution is successful, it returns 0, and the failure returns -1, the error code exists in Errno.

Additional information

Please refer to SETUID

SetFSGID (set the file system's unconssed code)

related functions

SetUID, Setreuid, Seteuid, SetFsuID

Header file

#include

Definition function

Int setfsgid (uid_t fsgid);

Function description

SetFSGID () is used to reset the file system of the current process file system. Under normal circumstances, the file system is identified by the FSGID and the effective component codes (EGID). If the super user calls this function, the parameter fsgID can be any value, otherwise the parameter fsgid must be one of the rules codes of Real / Effective / Saved. return value

If the execution is successful, it returns 0, and the failure returns -1, and the error code exists in Errno.

Additional information

This function is unique to Linux.

error code

Eperm permissions are not enough and cannot be completed.

SetFSUID (Setup file system user identification code)

related functions

SetUID, Setreuid, Seteuid, SetFSGID

Header file

#include

Definition function

INT setfsuid (UID_T FSUID);

Function description

SetFSUID () is used to reset the user identification code of the file system of the current process. In general, the user identification code (FSUID) of the file system is the same as the valid user identification code (EUID). If the super user calls this function, the parameter FSUID can be any value, otherwise the parameter FSUID must be one of the user identification code for REAL / EFFECTIVE / SAVED.

return value

If the execution is successful, it returns 0, and the failure returns -1, the error code exists in Errno.

Additional information

This function is unique to Linux

error code

Eperm permissions are not enough and cannot be completed.

Setgid (set the true unconssed code)

related functions

GETGID, SETREGID, GETEGID, SETEGID

Header file

#include

Definition function

Int setgid (GID_T GID);

Function description

Setgid () is used to set the true group identification code of the current process into a parameter GID value. If this call is performed as a hyperprise, REAL, EFFECTIVE and SavedGID will set a parameter GID.

return value

Set success, returns 0, and the failure returns -1, and the error code is stored in Errno.

error code

Eperm is not called by superuser, and the parameter GID is not one of the process's Effective GID or Saved GID values.

SetGrent (from the group data in the header reading group file)

related functions

getGrent, Endgrent

Header file

#include #include

Definition function

Void setgrent (void);

Function description

setGrent () is used to begin the read and write address of getGrent () to the beginning of the group file.

return value

Additional information

Please refer to SetPwent ().

SetGroups (Setup Group Code)

related functions

INITGROUPS, GETGROUP, GETGID, SETGID

Header file

#include

Definition function

INT setGroups (size_t size, const gid_t * list);

Function description

SetGroups () is used to add the group indicated in the list array to the group settings of the current process. The number of GID_Ts of the parameter size is List (), the maximum value is ngroup (32).

return value

Set success, returns 0, return -1 if there is an error.

error code

The efault parameter LIST array address is not legal. Eperm privilege must be that the root permissions EINVAL parameter size value is greater than NGroup (32).

SetPwent (account data from the first password file)

related functions

Getpwent, endpwent header file

#include #include

Definition function

Void setpwent (void);

Function description

setpwent () is used to refer to the read and write address of getpwent () back the password file.

return value

example

#include #include main () {struct passwd * user; int i; for (i = 0; i <4; i ) {user = getpwent (); printf (" % S:% D:% D:% S:% s:% s / n ", user-> pw_name, user-> pw_uid, user-> pw_gid, user-> pw_gecos, user-> pw_dir, user-> pw_shell ); setpwent (); user = getpwent (); printf ("% s:% d:% d:% s:% s:% s / n", user-> pw_name, user-> pw_uid, user-> PW_GID, USER-> PW_GECOS, USER-> PW_DIR, User-> Pw_shell); endpwent ();

carried out

Root: 0: 0: root: / root: / bin / Bashbin: 1: 1: bin: / bindaemon: 2: 2: daem: / sbinadm: 3: 4: adjm: / var / admroot: 0: 0: root : / root: / bin / bash

SetRegid (Set the true and valid grouping code)

related functions

Setgid, setEgID, setfsgid

Header file

#include

Definition function

INT setRegid (GID_T RGID, GID_T EGID);

Function description

SetRegID () is used to set the parameter RGID to the real group identification code of the current process, set the parameter EGID to the current process's valid group identification code. If the parameter RGID or EGID value is -1, the corresponding identification code will not change.

return value

If the execution is successful, it returns 0, and the failure returns -1, and the error code exists in Errno.

SetREUID (Set the true and valid user identification code)

related functions

SetUID, STEUID, SetFsuID

Header file

#include

Definition function

INT setUid (UID_T RUID, UID_T EUID);

Function description

SetREUID () is used to set the parameter ruid to the real user identification code of the current process, set the parameter EUID as a valid user identification code for the current process. If the parameter ruid or EUID value is -1, the corresponding identification code will not change.

return value

If the execution is successful, it returns 0, and the failure returns -1, and the error code exists in Errno.

Additional information

Please refer to SETUID ().

SetUID (Set the real user ID)

related functions

GetUid, Setreuid, SeteUId, SetFsuID

Header file

#include

Definition function

Int setuid (UID_T UID)

Function description

SetUID () is used to reset the user identification code that performs the current process. However, let this function active, its effective user identification code must be 0 (root). Under Linux, when root uses setUID () to transform into other user identification code, the root permissions will be discarded, which is completely converted into the user's identity, that is, the process will no longer have the right to setuid (). If it is just to abandon root permissions to temporarily, you must use STEUID (). return value

If the execution is successful, it returns 0, and the failure returns -1, and the error code exists in Errno.

Additional information

Generally in writing a program of SetUID root, in order to reduce the system security risks from such programs, it is recommended to perform setuid immediately after using the root permissions; to discard root privileges. In addition, the Linux system will not generate Core Dump when the process UID and EUID are inconsistent.

Setutent (login data from the UTMP file)

related functions

Getutent, Endutent

Header file

#include

Definition function

Void Setutent (Void);

Function description

Setutent () is used to refer the read and write address of the getutent () back to the UTMP file.

Additional information

Please refer to SetPWent () or setgrent ().

UTMPNAME (setting UTMP file path)

related functions

Getutent, GetId, Getutline, Setutent, Endutent, Pututline

Header file

#include

Definition function

Void utmpname (const char * file);

Function description

UTMPNAME () is used to set the path to the UTMP file to provide the access path for UTMP-related functions. If UTMPNAME () is not used, the default UTMP file path is / var / run / utmp.

return value

Crypt (encoded password or data)

related functions

GetPass

Header file

#define _xopen_source # incrude

Definition function

Char * Crypt (const char * key, const char * salt);

Function description

Crypt () will encode the string referred to by the parameter key using the Data Encryption Standard (DES) algorithm. The key string is only the first 8 characters, and the character of this length is meaningless. The parameter SALT is a string consisting of two characters, composed of A-Z, A-Z, 0-9, "." And "/" to determine which of the 4096 different internal tables. After the function is executed, it will return to the encoded string pointer, and the string referred to by the parameter key will not be fade. The encoded string length is 13 characters, the first two characters are the string represented by the parameter SALT.

return value

Returns a password string pointing to NULL.

Additional information

Plus -lcrypt is required when compiled with GCC.

example

#include main () {char passwd [13]; char * key; char slat [2]; key = getPass ("Input first password:"); slat [0] = key [0]; slat [1] = key [1]; strcpy (Passwd, Crypt (Key SLAT); key = getpass ("INPUT Second Password:"); SLAT [0] = passwd [0]; slat [1] = passwd [1 ]; Printf ("" After Crypt (), 1st Passwd:% S / N ", Passwd); Printf (" "After Crypt (), 2nd Passwd:% S / N", Crypt (Key SLAT);}

Input First Password: / * Enter TEST, after encoding, password, password, input test, password, password, will be the same * / after crypt () 1st passwd: teh0wlipw0gyqafter crypt () 2nd passwd: teh0wlipw0Gyq

BSearch (binary search)

related functions

Qsort

Header file

#include

Definition function

Void * bsearch (const void * key, const void * base, size_t nmemb, size_tsize, int (* company) (const void *, const void *));

Function description

BSearch () uses binary search to find data from the sorted array. The parameter key points to the key data to find, the parameter base points to the beginning address to be searched, the parameter NMEMB represents the number of elements in the array, and the size of each element is determined by the parameter size, the last parameter commit is a function pointer, This function is used to determine the size relationship between the two elements. If the element data refers to the element data referred to in the first parameter of the COMPAR, the element data referred to by the second parameter must return to the value greater than 0, two elements The data is equal to 0.

Additional information

Find the key data Return to the found address, return null if the critical data is not found in the array.

example

#include #include #define nmemb 5 # define size 10int compar (const void * a, const void * b) {return (strcmp ((char *) A, (char *) B ));} main () {char data [50] [size] = {"linux", "freebsd", "solaris", "sunos", "windows"}; char key [80], * base, * offset ; int i, nmemb = nmemb, size = size; while (1) {printf (">"); FGETS (key, sizeof (key), stdin; key [strlen (key) -1] = '/ 0' ; if (! strcmp (key, "exit")) Break; if (! Strcmp (key, "list")) {for (i = 0; i

> Hello / * Enter Hello Strings * / Hello NOT Found! / * Can't find the Hello string * / add hello to data array / * Add Hello strings to * />. list / * list all data * / freebsdlinuxSolarissunosWindowshello > Hellofound: Hello

LFIND (linear search)

related functions

LSearch

Header file

#include

Definition function

Void * Lfind (const void * key, const void * base, size_t * nmemb, size_tsize, int (*) (const void *, const void *));

Function description

LFIND () uses linear searches to find data from beginning to end from beginning to end. The parameter key points to the key data to find, the parameter base points to the beginning address to be searched, the parameter NMEMB represents the number of elements in the array, and the size of each element is determined by the parameter size, the last parameter commit is a function pointer, This function is used to determine whether the two elements are the same. If the element data referred to by the off-plane parameter refers to the COMPAR, the element data refers to the element data referred to by the second parameter, then returns 0, the two element data is different, return non-0 value. LFIND () and LSearch () Different points are that LFIND () will only return null when the critical data is not found, and the data will not be actively added to the end of the array.

return value

Find the key data Return the address of the found element, if you find the critical data in an array, return to the null pointer (NULL).

example

Refer to LSearch ().

LSEARCH (linear search)

related functions

Lfind

Header file

#include

Definition function

Void * LSearch (const void * key, const void * base, size_t * nmemb, size_t size, int (* company) (const void *, const void *); function description

LSEARCH () uses linear search in an array from head to one item. The parameter key points to the key data to find, the parameter base points to the beginning address to be searched, the parameter NMEMB represents the number of elements in the array, and the size of each element is determined by the parameter size, the last parameter commit is a function pointer, This function is used to determine whether the two elements are the same. If the element data refers to the element data referred to in the first parameter refers to the first parameter of the COMPAR, then returns 0, the two element data is different, return non- 0 value. If LSEARCH () does not find critical data, the data will be actively added to the array.

return value

Finding the key data Returns the limbs of the found element, if you can't find critical data in an array, add this critical data to an array, and then return the addointed address after the array.

example

#include #include #define nmemb50 # define size 10int compar (comst void * a, const void * b) {return (strcmp ((char *) A, (char *) B )));} main () {char data [NMEMB] = {"linux", "freebsd", "solzris", "sunos", "windows"}; char key [80], * base, * offset ; int I, nmemb = nmemb, size = size; for (i = 1; i <5; i ) {FGETS (key, sizeof9key), stdin; key [strlen (key) -1] = '/ 0'; Base = data [0]; offset = (char *) LFIND (Key, Base, & NMEMB, SIZE, COMPAR); if (Offset == Null) {Printf ("% s not found! / n"; offset = (char *) LSearch (Key, Base, & NMEMB, SIZE, COMPAR); Printf ("Add% S to Data Array / N", Offset);} else {Printf ("Found:% S / N", Offset) }}}

carried out

Linuxfound: LinuxOS / 2OS / 2 Not Found! Add OS / 2 To Data Arrayos / 2Found: OS / 2

Qsort (using rapid sorting method) array)

related functions

BSearch

Header file

#include

Definition function

Void Qsort (void * base, size_t nmemb, size_t size, int (condition void *, const void *);

Function description

Parameter base points to the beginning address of the array, parameter NMEMB represents the number of elements in the array, the size of each element is determined by the parameter size, the last parameter commit is a function pointer, this function is used to determine the two elements Large relationship, if the element data referred to by the first parameter referred to in CoMPAR is greater than the element data referred to by the second parameter, the value of greater than zero must be sent back, and the two element data is equal to zero.

return value

Additional information

example

#define nmemb7 # include int compar (const void * a, const void * b) {int * aa = (int *) a, * bb = (int *) b; if (* aa> * BB) RETURN 1; if (* aa == * bb) Return 0; if (* aa <* bb) return -1;} main () {int base [nmemb] = {3, 102, 5, -2, 98, 52, 18}; int 1; for (i = 0; i

3 102 5 -2 98 52 18-2 3 ​​5 18 52 98 102

Rand (generating random)

related functions

Srand, Random, Srandom

Header file

#include

Definition function

Int Rand (Void)

Function description

Rand () will return a random value and range between 0 to Rand_max. Before calling this function, it is necessary to use SRAND () to set the random number. If the random number seed is not set, the rand () will automatically set the random number seed when the random number is 1. For the random number, please refer to SRAND ().

return value

Returns the random value between 0 to RAND_MAX, and Rand_max is defined in STDLIB.H, its value is 2147483647.

example

/ * Generate a random value between 1 and 10, this example does not have a random number seed, a complete random number, please refer to SRAND () * / # include main () {INT I, J; for (i = 0; i <10; i ) {j = 1 (int) (10.0 * rand () / (rand_max 1.0)); Printf ("% d", j);}}

carried out

9 4 8 8 10 2 4 8 3 69 4 8 8 10 2 4 8 3 6

SRAND (set random seed)

related functions

Rand, Random Srandom

Header file

#include

Definition function

Void Srand (unsigned int seed);

Function description

SRAND () is used to set random number when random number is generated. Parameters SEED must be an integer, usually use the return value of GEYPID () or TIME (0) to do SEED. If each SEED has the same value, the random value generated by the rand () will be the same.

return value

example

/ * Generate random values ​​between 1 and 10, this example and execution result can be with RAND () reference * / # include #include main () {INT I, J; SRAND (INT) TIME (0)); for (i = 0; I <10; i ) {j = 1 (int) (10.0 * rand () / (rand_max 1.0)); Printf ("% D" , J);}}

carried out

5 8 8 8 10 2 10 8 9 92 9 7 4 10 3 2 10 8 7

Close (close file)

related functions

Open, fcntl, shutdown, unlink, fclose header file

#include

Definition function

INT Close (INT FD);

Function description

If you are no longer needed after using the file, you can use Close () to turn off the file, and the two close () will let the data write back the disk and release the resources occupied by the file. The parameter fd is the file description word previously returned by Open () or CREAT ().

return value

Returns 0 if the file is smooth, return -1 when an error occurs.

error code

EBADF parameter fd non-effective file descriptor or the file is closed.

Additional information

Although the system will automatically close the open files, it is recommended to check the return value itself.

example

Reference open ()

Creat (create file)

related functions

Read, Write, Fcntl, Close, Link, Stat, Umask, UNLINK, FOPEN

Header file

#include #include #include

Definition function

INT Creat (const char * pathname, mode_tmode);

Function description

Parameter Pathname points to the file path string to be established. Creat () is equivalent to calling Open () open (on (const char * pathname, (o_creat char * pathname, (o_creat | o_wronly | o_trunc)) using the following call mode;

error code

For parameter mode, please refer to the open () function.

return value

Creat () will return a new file descriptor, if there is an error, it will return -1 and set the error code to Errno. The file indicated by the EEXIST parameter Pathname already exists. EACCESS Parameters Pathname The file specified by the file does not meet the required permity Erofs to open the write permission file exists in the read-only file system EFault parameter Pathname pointer exceeds the accessible memory space Einval parameter MODE is incorrect. ENAMETOOLONG parameter Pathname is too long. ENOTDIR parameter Pathname is a directory ENOMEM core memory instead of ELOOP parameter pathaname has excessive symbolic connection issues. Emfile has reached the process to open the number of files that can open at the same time Enfile has reached the limit of the number of files that can be opened at the same time.

Additional information

Creat () Unable to establish a special device file, if you need to use MKNOD ().

example

Please refer to Open ().

DUP (copy file description word)

related functions

Open, Close, FCNTL, DUP2

Header file

#include

Definition function

INT DUP (INT OLDFD);

Function description

DUP () used to copy the file descriptor referred to in the parameter Oldfd and return it. This new file description word and parameter Oldfd refers to the same file, sharing all lock, read and write location, and privileges or flags. For example, when using Lseek () describes the word effect on a file, the read and write position of another file description word will also change. However, the file description word does not share the Close-ON-EXEC flag.

return value

When the copy is successful, the minimum and unused file descriptive words are returned. Returns -1, Errno will save the error code. Error code EBADF parameter fd non-valid file descriptor, or the file is closed.

DUP2 (copy file descriptor)

related functions

Open, Close, FCNTL, DUP

Header file

#include

Definition function

INT DUP2 (INT ODLFD, INT NEWFD);

Function description

DUP2 () is used to copy the file descriptor referred to in the parameter Oldfd, and copy it to the parameter newfd. If the parameter newfd is an open file descriptor, the file referred to in Newfd will be closed first. Document Description Words replicated by DUP2 (), share various file status with the original file description words, details can be referred to DUP ().

return value

When the copy is successful, the minimum and unused file descriptive words are returned. Returns -1, Errno will save the error code.

Additional information

DUP2 () is equivalent to calling FCNTL (OLDFD, F_DUPFD, NewFD); refer to FCNTL ().

error code

EBADF parameter fd non-effective file descriptor, or this file is closed

FCNTL (file description word operation)

related functions

Open, FLOCK

Header file

#include #include

Definition function

INT FCNTL (INT FD, INT CMD); int FCNTL (INT FD, INT CMD, Long Arg); int FCNTL (INT FD, INT CMD, Struct Flock * Lock);

Function description

Fcntl () is used to operate some of the features of the file description word. The parameter fd represents the file description word, parameter cmd represents the instructions that want to operate. There are several situations: f_dupfd is used to find the smallest and still unused file descriptive words greater than or equal to parameter Arg, and copy the file descriptor of the parameter FD. Perform success, return to the newly copied file descriptor. Please refer to DUP2 (). F_getfd gets a Close-ON-EXEC flag. If the FD_CLOEXEC bit of this flag is 0, the file will not be closed when the exec () related function is called. F_setfd Sets the Close-ON-EXEC flag. The flag is determined by the FD_CLOEXEC bit of parameter arg. F_GETFL acquires the file description word status flag, this flag is Open () parameter flags. F_setfl Settings File Description Word Status Flag, parameter arg is a new flag, but only allows O_APpend, O_nonBlock, and O_async bits to change, other bit changes will not be affected. F_getlk acquires the status of the file lock. F_setlk Sets the status of the file locked. At this time, the L_TYPE value of the FLCOK structure must be f_rdlck, f_wrlck, or f_unlck. If you cannot establish a lock, return -1, error code is EACCES or EAGAIN. F_setlkw f_setlk is the same, but when lock is unable, this call will continue until the locking action is successful. If the signal is interrupted during the waiting to be locked, -1 is returned immediately, and the error code is EINTR. The parameter LOCK pointer is the FLOCK structure pointer, defines the following Struct flcok {short int l_type; / * lock status * / short int L_whence; / * determine the L_Start position * / off_t l_start; / * The beginning position of the lock area * / OFF_T L_LEN; / * The size of the lock area * / pid_t l_pid; / * Lock action process * /}; l_type has three states: F_RDLCK creates a locking F_WRLCK to create a lock-in-use lock f_unlck before delete There are also three ways of l_whens: Seek_set begins with the beginning of the lock. Seek_cur SEEK_END is the locked start position with the current file read and write position as the lock.

return value

Success returns 0, if there is an error, return -1, the error is existed in Errno.

FLOCK (Lock file or unlock) related functions

Open, FCNTL

Header file

#include

Definition function

Int flock (int fd, int operation);

Function description

FLOCK () will make a variety of lockup or unlocked the files referred to by the parameter FD as specified by the parameter operation. This function can only lock the entire file and cannot lock a certain area of ​​the file.

parameter

Operation has the following four situations: LOCK_SH Establish a shared lock. Multiple processes can share the same file simultaneously. Lock_ex establishes a mutex lock. A file is only one mutually exclusive lock. Lock_un releases the file lock status. When LOCK_NB cannot establish a lock, this operation can be blocked and the process will be returned immediately. It is usually a combination of or (|) with LOCK_SH or LOCK_EX. A single file cannot establish a shared lock and mutex lock, while the file descriptor does not inherit this lock when using DUP () or fork ().

return value

Returns 0 means success, if there is an error, return -1, the error code exists in Errno.

FSYNC (writing buffer data back)

related functions

Sync

Header file

#include

Definition function

INT FSYNC (INT FD);

Function description

fsync () is responsible for writing the file data referred to by the parameter FD, writes the disk by the system buffer to ensure data synchronization.

return value

Success returns 0, the failure returns -1, errno is the error code.

Lseek (reading and writing location of mobile file)

related functions

DUP, OPEN, FSEEK

Header file

#include #include

Definition function

OFF_T LSEEK (int Fildes, OFF_T Offset, INT imce);

Function description

Each open file has a read and write location. When the file is opened, its read and write position is to point to the file. If the file (such as O_Append) is opened in an additional manner, the reading and writing location will point to the file end. When Read () or Write (), the read and write position will increase, Lseek () is used to control the read and write location of the file. Parameters Fildes For open file descriptors, parameter OFFSET is the number of displacements that move the read-write position based on parameter imines.

parameter

The use is one of the following: seek_set parameter offset is a new read and write location. Seek_cur increases OFFSET unloading after the current read and write position. Seek_end points the read-write position to the end of the file and increases OFFSET. When the WHENCE value is SEEK_CUR or SEEK_END, the parameter OFFET allows the emergence of negative values. The following is a special way of use: , Seek_end); 3) Want to get the current file location: Lseek (int Fildes, 0, seek_cur);

return value

When the call is successful, return the current read and write position, which is the number of bytes from the beginning of the file. Returns -1, Errno will save the error code.

Additional information

The Linux system does not allow Lseek () to the TTY device, and this action will return LSEEK () returns Espipe.

example

Reference this function

MKSTEMP (establish a unique temporary file)

related functions

MkTemp

Header file

#include Definition function

INT MKSTEMP (Char * Template);

Function description

MKSTEMP () is used to establish a unique temporary file. The last six characters in the file name string referred to in the parameter template must be xxxxxx. MKSTEMP () will open this file with readable write mode and 0600 permissions. If the file does not exist, the file will be established. After opening this file, its file description word will return. After the file is successfully opened, return to the readable write file descriptor. If the file opens fails, returns NULL and exists in Errno in Errno.

error code

The last six characters of the EINVAL parameter template string are non-xxxxxx. EEXIST cannot establish temporary files.

Additional information

The file name string referred to the parameter template must be declared as array, such as: char template [] = "template-xxxxxx"; Never use the following expressions char * Template = "template-xxxxxx";

example

#include main () {int fd; char template [] = "template-xxxxxx"; fd = mkstemp (template); Printf ("Template =% S / N", Template; Close (FD) }

carried out

Template = Template-LGZCBO

Open (Open File)

related functions

Read, Write, Fcntl, Close, Link, Stat, Umask, UNLINK, FOPEN

Header file

#include #include #include

Definition function

INT Open (const char * pathname, int flags); int open (const char * pathname, int flags, mode_t mode);

Function description

Parameter Pathname points to the file path string to open. The following is the flags that the parameter flags can use: o_rdonly opens files o_wronly in a read-only mode O_RDWR to open files with write-to-write mode. The above three kinds of flags are mutually exclusive, that is, they cannot be used simultaneously, but can be combined with the following flags. O_Creat If the file wants to open does not exist, the file is automatically created. O_EXCL If O_CREAT is also set, this instruction will check if the file exists. If there is no existence, set this file, otherwise it will cause an open file error. In addition, if o_creat is set simultaneously, and if you want to open the file as a symbolic connection, the file failed to open. O_NOCTTY If the file wants to open as a terminal device, the terminal does not operate the terminal as a process control terminal. O_Trunc If the file exists and is open in a writable manner, this flag will make the file length of 0, and the information stored in this file will also disappear. O_Append When reading and writing a file, start moving from the file at the end, that is, the data written will be added behind the file in addition. O_nonblock opens files in a non-blocking manner, that is, if there is any data reading or waiting, it will return to the process immediately. O_ndlay is O_NONBLOCK. O_Sync opens the file in a synchronous manner. O_nofollow If the file referred to by the parameter pathname is a symbolic connection, the open file will fail. O_Directory If the file refers to the parameter pathname is not a directory, the open file will fail. This is a featured flag after Linux2.2 to avoid some system security issues. The parameter Mode has the following several combinations, only when the new file is created, and the permissions when the file really built will be affected by the umask value, so the file permission should be (Mode-Umaks). S_IRWXU00700 Permissions, representing the file owner has readable, writable and executable permissions. S_IRUSR or S_IREAD, 00400 Permissions represent that the file owner has readable permissions. S_IWUSR or S_IWRITE, 00200 permissions, representing the file owner has writable permissions. S_IXUSR or S_IEXEC, 00100 Permissions, representing the file owner has executable permissions. S_IRWXG 00070 Permissions represent that the file user group is readable, writable and executable. S_IRGRP 00040 Permissions represents the file user group with readable permissions. S_IWGRP 00020 permissions represent that the file user group has writable permissions. S_ixgrp 00010 permissions represents the file user group with executable permissions. S_IRWX00007 Permissions, representing other users with readable, writable, and executable permissions. S_IROTH 00004 Permissions, representing other users with readable permissions S_IWoth 00002 permissions, representing other users with writable permissions. S_ixoth 00001 permissions, representing other users with executable permissions. return value

If all the permissions to be verified, the 0 value is returned, and the success is successful, and only -1 is returned if there is a permission.

error code

The file indicated by the EEXIST parameter Pathname exists, but the O_CREAT and O_EXCL flag are used. The file referred to in the EACcess parameter Pathname does not meet the permissions required for the test. Erofs wants to test files that write authorities exist within read-only file systems. The EFAULT parameter Pathname pointer exceeds the accessible memory space. The EINVAL parameter mode is incorrect. ENAMETOOLONG parameter Pathname is too long. Enotdir parameter pathname is not a directory. EnomeM core is insufficient. Eloop parameter pathname has excessive symbolic connection issues. EIO I / O Access error.

Additional information

The judgment of using Access () to operate should be particularly careful, such as after Access (), then Open () empty files may cause system security issues. example

#include #include #include #include main () {Int fd, size; char s [] = "Linux Programmer! / N ", buffer [80]; fd = open (" / tmp / temp ", o_wronly | o_creat); Write (FD, S, SIZEOF (S)); Close (fd); fd = open (" / TMP / Temp ", o_rdonly); size = read (fd, buffer, sizeof (buffer); Close (FD); Printf ("% s ", buffer);}

carried out

Linux Programmer!

READ (read data from the file that has been opened)

related functions

READDIR, WRITE, FCNTL, Close, Lseek, Readlink, FREAD

Header file

#include

Definition function

SSIZE_T READ (INT FD, VOID * BUF, SIZE_T COUNT);

Function description

READ () will transfer the file referred to by the parameter FD to the memory in the BUF pointer to the buf pointer. If the parameter count is 0, read () does not have a function and returns 0. The return value is the number of bytes that actually read. If 0 is returned, it indicates that the file has been reached or an unreadable data, and the file read and write position will be moved with the byte.

Additional information

If Returning read () will return the number of bytes that actually read, it is best to compare the return value with the parameter count, if the number of bytes returned is less than the number of bytes read, it is possible to read the file end. Read from the pipe (PIPE) or terminal, or READ () is interrupted by the signal. When there is an error, Returns -1, the error code is stored in errno, and the file read and write position cannot be expected.

error code

EINTR This call is interrupted by the signal. Eagain Returns this value if you do not block I / O (o_nonblock). EBADF parameter fd non-active file descriptor, or the file is closed.

example

Refer to Open ().

SYNC (writing buffer data)

related functions

Fsync

Header file

#include

Definition function

Int Sync (Void)

Function description

Sync () is responsible for writing the system buffer data back to the disk to ensure data synchronization.

return value

Returns 0.

Write (write data into open file)

related functions

Open, Read, Fcntl, Close, Lseek, Sync, Fsync, FWRITE

Header file

#include

Definition function

SSIZE_T WRITE (INT FD, Const Void * BUF, SIZE_T Count);

Function description

Write () will write the memory referred to in the parameter BUF to the file referred to in the parameter FD. Of course, the file read and write position will also move.

return value

If WRITE () will return the number of bytes that are actually written. When there is an error, -1 is returned, and the error code is stored in Errno.

error code

EINTR This call is interrupted by the signal. Eagain Returns this value if you do not block I / O (o_nonblock). EADF parameter fd non-active file descriptor, or the file is closed. example

Please refer to Open ().

Clearerr (Clearing the bundle of the file stream)

related functions

Feof

Header file

#include

Definition function

Void Clearerr (File * Stream);

Function description

Clearerr () Clears the bugt of the bugling used by the file stream specified by the parameter stream.

return value

Fclose (close file)

related functions

Close, Fflush, Fopen, SetBUF

Header file

#include

Definition function

Int fclose (file * stream);

Function description

Fclose () is used to close the previous FOPEN () open file. This action will allow the data in the buffer to write in the file and release the file resources provided by the system.

return value

If the file action is successful, it returns 0. When there is an error, EOF is returned and the error code is stored to Errno.

error code

Ebadf represents the parameter stream non-open file.

example

Please refer to FOpen ().

FDOPEN (transfer file description words to file pointer)

related functions

Fopen, Open, Fclose

Header file

#include

Definition function

FILE * FDOPEN (int Fildes, Const Char * MODE);

Function description

FDOpen () will return the file description word of the parameter Fildes to the corresponding file pointer. The parameter MODE string represents the flow of the file pointer, which must be the same as the original file description word read and write mode. For the MODE string format, please refer to FOpen ().

return value

When the conversion is successful, return to the file pointer to the stream. Failure returns NULL and exists in errno in Errno.

example

#include main () {file * fp = fdopen (0, "w "); FPRINTF (FP, "% S / N", "Hello!"); fclose (fp);}

carried out

Hello!

FeOf (check if the file flow reads the file end)

related functions

Fopen, Fgetc, Fgets, FREAD

Header file

#include

Definition function

INT Feof (File * Stream);

Function description

Feof () is used to detect whether the file pointer returned by the file end and the mantissa stream is FOPEN (). If a non-zero value is returned to the file, it returns 0.

return value

Returns a non-zero value representative has arrived at the end of the file.

FFlush (Update Buffer)

related functions

Write, Fopen, Fclose, SetBUF

Header file

#include

Definition function

INT fflush (file * stream);

Function description

Fflush () will force the data in the buffer to write back the parameter stream specified. If the parameter stream is null, fflush () updates all open file data.

return value

Successfully returned 0, failed to return EOF, and the error code is existed in Errno.

error code

The file specified by the eBadf parameter stream is not opened, or the state is read-only. Other error code reference WRITE (). FGETC (read a character in the file)

related functions

Open, FREAD, FSCANF, GETC

Header file

INCLUDE

Definition function

NT fgetc (file * stream);

Function description

FGETC () reads a character from the file referred to in the parameter stream. Returns EOF if you read the file end and countless.

return value

Getc () will return to read characters. If returns EOF, the file is indicated.

example

#include main () {file * fp; int C; fp = fopen ("exist", "r"); while ((c = fgetc (fp))! = EOF) Printf ("% C) ", C); fclose (fp);

FGETS (read a string in the file)

related functions

Open, FREAD, FSCANF, GETC

Header file

INCLUDE

Definition function

HAR * FGETS (Char * S, INT SIZE, FILE * STREAM);

Function description

FGETS () is used to read the character from the file referred to by the parameter stream to the memory space referred to as the parameter S, until the charter characters appear, read the file tail or read the size-1 character, and finally add NULL ends as the string.

return value

Gets () Returns the S pointer if successful, and returns NULL indicates that there is an error.

example

#include main () {char s [80]; FPUTS (FGETS (S, 80, Stdin), Stdout;

carried out

THIS IS A TEST / * Input * / this is a test / * output * /

Fileno (return file description word used by file flow)

related functions

Open, FOPEN

Header file

#include

Definition function

Int fileno (file * stream);

Function description

Fileno () used to obtain the file descriptor used by the file stream specified by the parameter stream.

return value

Returns the file descriptor.

example

#include main () {file * fp; int fd; fd; fp = fopen ("/ etc / passwd", "r"); fd = fileno (fp); Printf ("fd =% D / N ", Fd); fclose (fp);

carried out

FD = 3

FOpen (Open File)

related functions

Open, FCLOSE

Header file

#include

Definition function

FILE * FOPEN (Const Char * Path, Const Char * Mode);

Function description

The parameter PATH string contains file paths and file names that want to open, and the parameter MODE string represents the flow form. Mode has several form strings: r opens read-only files, which must exist. R opens readable files, which must exist. w open only write files, if the file exists, the file length is 0. The content of the file will disappear. This file is created if the file does not exist. W opens the readable and writable file. If the file exists, the file length is zero, that is, the content of the file will disappear. This file is created if the file does not exist. a opens only the file in an additional manner. If the file does not exist, the file is created. If the file exists, the write data will be added to the file, that is, the original content will be retained. A opens readable files in addition. If the file does not exist, the file will be created. If the file exists, the written data will be added to the end of the file, that is, the file original content will be retained. The above-described form strings can add a B character, such as RB, W B or AB , etc., add B characters to tell the function library open files for binary files, not pure text files. However, in the POSIX system, it contains Linux to ignore the character. The new file established by fopen () will have S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH (0666) permissions, this file permission will also refer to the umask value. return value

After the file is smooth, the file pointer to the stream will be returned. If the file opens fails, returns NULL and exists in Errno in Errno.

Additional information

In general, the action will be read or written after the file is opened. If the file fails, the next read and write movement cannot be carried out smoothly, so it is incorrectly determined and processed after fopen ().

example

#include main () {file * fp; fp = fopen ("noexist", "a "); if (fp = = null) return; fclose (fp);}

FPUTC (write a specified character in the file stream)

related functions

Fopen, Fwrite, Fscanf, PUTC

Header file

#include

Definition function

INT FPUTC (INT C, FILE * stream);

Function description

The FPUTC will turn the parameter c to the unsigned char to write into the file specified by the parameter stream.

return value

FPUTC () will return to write successful characters, ie the parameter c. If you return EOF, you will fail.

example

#include main () {file * fp; char A [26] = "AbcdefghijklmnopqrStuvwxyz"; int I; fp = fopen ("noexist", "w"); for (i = 0; i <26 ; i ) FPUTC (a [i], fp); fclose (fp);}

FPUTS (write a specified string to the file)

related functions

Fopen, Fwrite, Fscanf, FPUTC, PUTC

Header file

#include

Definition function

INT FPUTS (Const Char * S, File * Stream);

Function description

FPUTS () is used to write a string referred to in the parameter S to the file referred to in the parameter stream.

return value

If success, return the number of characters written, returning EOF, indicating that there is an error.

example

Please refer to Fgets ().

FREAD (read data from file stream)

related functions

Fopen, fwrite, fseek, fscanf header file

#include

Definition function

SIZE_T FREAD (Void * PTR, SIZE_T SIZE, SIZE_T NMEMB, FILE * stream);

Function description

FREAD () is used to read data from the file stream. The parameter stream is the open file pointer, the parameter PTR points to the data space you want to read, and the read characters are determined by the parameter size * nmemb. FREAD () will return the number of NMEMBs actually read. If this value is smaller than the parameter NMEMB, the representative may read the file or have an error. At this time, you must use FeOf () or fError () to determine what happens .

return value

Returns the number of NMEMBs that actually read.

Additional information

example

#include #define nmemb 3struct test {char name [20]; int size;} s [NMEMB]; main () {file * stream; int i; stream = fopen ("/ tmp / fwrite", "R"); Fread (S, SIZEOF (Struct Test), NMEMB, Stream); Fclose (stream); for (i = 0; i

carried out

Name [0] = linux! size [0] = 6name [1] = freebsd! size [1] = 8name [2] = Windows2000 size [2] = 11

Freopen (Open File)

related functions

Fopen, fclose

Header file

#include

Definition function

FILE * FREOPEN (Const Char * Path, Const Char * Mode, File * Stream);

Function description

Parameter Path string contains file paths and file names that want to open, and parameter mode Please refer to the fopen (). The parameter stream is the open file pointer. Freopen () will close the file stream opened by the original Stream and open the file of the parameter path.

return value

After the file is smooth, the file pointer to the stream will be returned. Returns NULL if the file is open, and the error code is in Errno.

example

#include main () {file * fp; fp = fopen ("/ etc / passwd", "r"); fp = flEopen ("/ etc / group", "r", fp); fclose (fp);

FSEEK (reading and writing location of mobile file stream)

related functions

Rewind, Ftell, Fgetpos, FSETPOS, LSEEK

Header file

#include

Definition function

Int fseek (file * stream, long offset, int imce);

Function description

FSeek () used to move the read and write location of the file stream. The parameter stream is the opened file pointer, and the parameter OFFSET is the number of displacements that move the read-write position based on the parameter imines.

parameter

The use is one of the following: Seek_set from the beginning OFFSET displacement of the file as a new read and write location. Seek_cur increases OFFSET unloading after the current read and write position. Seek_end points the read-write position to the end of the file and increases OFFSET. When the WHENCE value is seek_cur or seek_ek_ek_ek_end, the parameter OFFSET allows the emergence of negative values. The following is a more special way: 1) When you move the read / write position to the beginning of the file: FSeek (File * Stream, 0, Seek_set); 2) When you move the read / write location to the file: FSeek (File * stream 0, 0seek_end; return value

When the call is successful, it returns 0. If there is an error, return -1, Errno will save the error code.

Additional information

FSeek () is unlike LSeek () will return a read-write location, so you must use ftell () to achieve the current read and write location.

example

#include main () {file * stream; long offset; fpos_t pos; stream = fopen ("/ etc / passwd", "r"); FSEEK (Stream, 5, seek_set); Printf ("Offset =% D / N ", Ftell (stream); ref (stream); FgetPos (Stream, & POS); Printf (" OFFSET =% D / N ", POS); POS = 10; FSETPOS (Stream, & POS); Printf ("OFFSET =% D / N", Ftell (Stream); fclose (stream);}

carried out

OFFSET = 5Offset = 0Offset = 10

Ftell (acquired the reading location of the file stream)

related functions

FSeek, Rewind, Fgetpos, FSETPOS

Header file

#include

Definition function

Long Ftell (File * Stream);

Function description

ftell () is used to obtain the current read and write location of the file stream. The parameter stream is the open file pointer.

return value

When the call is successful, return to the current read and write position. If there is an error, return -1, errno will save the error code.

error code

Ebadf parameter stream is invalid or removable of file streams for read-write locations.

example

Refer to FSeek ().

FWRITE (write data to file stream)

related functions

Fopen, Fread, FSeek, Fscanf

Header file

#include

Definition function

SIZE_T FWRITE (const void * ptr, size_t size, size_t nmemb, file * stream);

Function description

FWRITE () is used to write data into the file stream. The parameter stream is the open file pointer, the parameter PTR pointing to the data address to be written, and the total written character is determined by the parameter size * NMEMB. FWRITE () will return NMEMB numbers that are actually written.

return value

Returns the number of NMEMBs actually written.

example

#include #define set_s (x, y) {strcoy (s [x] .name, y); s [x] .size = strlen (y);} # define nmemb 3struct test {char name [ 20]; int size;} s [NMEMB]; main () {file * stream; set_s (0, "Linux!"); Set_s (1, "freebsd!"); Set_s (2, "windows2000."); Stream = FOPEN ("/ TMP / FWRITE", "W"); FWRITE (S, SIZEOF (Struct Test), NMEMB, Stream); Fclose (stream);}

Refer to FREAD ().

Getc (read a character in the file)

related functions

READ, FOPEN, FREAD, FGETC

Header file

#include

Definition function

INT GETC (File * stream);

Function description

Getc () is used to read a character from the file referred to by parameter stream. Returns EOF if you read the file end and countless. Although Getc () is the same as the FGetc (), getc () is a macro definition, a non-real function call.

return value

Getc () will return to read characters. If returns EOF, the file is indicated.

example

Refer to FGETC ().

GetChar (read in the standard input device)

related functions

Fopen, Fread, Fscanf, Getc

Header file

#include

Definition function

INT getchar (void);

Function description

GetChar () is used to read a character from a standard input device. The character is then returned from the unsigned char to INT.

return value

GetChar () will return to the read character. If you return EOF, an error occurs.

Additional information

GetChar () is a true function, but a Getc (stdin) macro definition.

example

#include main () {file * fp; int C, i; for (i = 0li <5; i ) {c = getchar (); PUTCHAR (C);}}

carried out

1234 / * Enter * / 1234 / * Output * /

Gets (read into a string from the standard input device)

related functions

Fopen, Fread, Fscanf, Fgets

Header file

#include

Definition function

Char * gets (char * s);

Function description

Gets () used to read characters from the standard device and save the memory space referred to as the parameter S, until the wrap character is displayed or read to the end of the file, and finally add NULL to the end of the string.

return value

Gets () Returns the S pointer if successful, and returns NULL indicates that there is an error.

Additional information

Since getS () cannot know the size of the string S, you must encounter a wrap character or file tail will end the input, so it is easy to cause a security problem of buffer overflow. It is recommended to use FGETS () to replace it.

example

Reference fgets ()

MkTemp (produced a single temporary file name)

related functions

TMPFILE

Header file

#include

Definition function

Char * mktemp (char * template);

Function description

MkTemp () is used to generate a unique temporary file name. The last six characters in the file name string referred to in the parameter template must be xxxxxx. The resulting file name will be returned by the string pointer.

return value

After the file is smooth, the file pointer to the stream will be returned. Returns NULL if the file is open, and the error code is in Errno. Additional information

The file name string refers to the parameter Template must be declared as array, such as: char template [] = "template-xxxxxx"; non-use char * template = "template-xxxxxx";

example

#include main () {char template [] = "template-xxxxxx"; mktemp (template); Printf ("Template =% S / N", Template);}

PUTC (write a specified character in the file)

related functions

Fopen, Fwrite, Fscanf, FPUTC

Header file

#include

ATEXIT (Set the function called before the program ends)

related functions

_EXIT, EXIT, ON_EXIT

Header file

#include

Definition function

INT ATEXIT (VOID) (VOID));

Function description

Atexit () is used to set the function called before the program is ended. When the program returns exit () or returning from the main, the function specified by the parameter function will be called first, and then the program is actually ended by the exit ().

return value

If the execution is successful, it returns 0, otherwise returns -1, and the cause is existed in Errno.

example

#include void my_exit (void) {printf ("Before exit ()! / n");} main () {atExit (MY_EXIT); exit (0);}

carried out

BEFORE EXIT ()!

EXECL (executable)

related functions

Fork, Execle, Execlp, Execv, Execve, EXECVP

Header file

#include

Definition function

Int Execl (Const Char * Path, Const Char * Arg, ....);

Function description

EXECL () is used to perform the file path represented by the parameter Path string, and the next parameter represents the past Argv (0), Argv [1] ..., the last parameter must be empty pointer (NULL) End.

return value

If the function does not return, the function will not return, and the execution failed, returned to -1, and the cause is existed in Errno.

example

#include main () {execl ("/ bin / ls", "ls", "- al", "/ etc / passwd", (char *) 0);

carried out

/ * Execution / BIN / LS -AL / ETC / Passwd * / - RW-R - R - 1 Root Root 705 Sep 3 13: 52 / etc / passwd

EXECLP (Find files from the PATH environment variable)

related functions

Fork, Execl, Execle, Execv, Execve, Execvp

Header file

#include

Definition function

Int Execlp (const char * file, const char * arg, ...);

Function description

EXECLP () will find the file name that meets the parameter file from the directory referred to by the PATH environment variable. After finding it, then execute the file, then the second future parameter as the Argv [0], Argv [1] ... ..., the last parameter must end with an empty pointer (NULL). return value

If the function does not return, the function will not return, and the execution failed, returned to -1, and the cause is existed in Errno.

error code

Refer to EXECVE ().

example

/ * Execute ls -al / etc / passwd execlp () to find / bin / bin in the PATH variable / bin / ls * / # include main () {EXECLP ("LS", "LS", " -Al "," / etc / passwd ", (char *) 0);

carried out

-rw-r - r - 1 root root 705 Sep 3 13: 52 / etc / passwd

EXECV (executable)

related functions

Fork, Execl, Execle, Execlp, Execve, EXECVP

Header file

#include

Definition function

INT EXECV (const char * path, char * const argv []);

Function description

Execv () is used to perform the file path represented by the parameter Path string, and the exeCL () is different in Execve () only two parameters, and the second parameter uses the array pointer to pass to the execution file.

return value

If the function does not return, the function will not return, and the execution failed, returned to -1, and the cause is existed in Errno.

error code

Please refer to Execve ().

example

/ * Execute / bin / ls -al / etc / passwd * / # include main () {char * argv [] = {"ls", "- al", "/ etc / passwd", CHAR *)}}; Execv ("/ bin / ls", argv);

carried out

-rw-r - r - 1 root root 705 Sep 3 13: 52 / etc / passwd

Execve (execution file)

related functions

Fork, Execl, Execle, Execlp, Execv, EXECVP

Header file

#include

Definition function

Int Execve (const char * filename, char * const argv [], char * const envp [];

Function description

Execve () is used to perform the file path represented by the parameter filename string. The second parameter system uses the array pointer to pass to the execution file, and the last parameter is an array of new environment variables passed to the execution file.

return value

If the function does not return, the function will not return, and the execution failed, returned to -1, and the cause is existed in Errno.

error code

EACCES1. The files that do not have users do not have user executable permissions. 2. The file system to which the file to be performed is hung in a Noexec mode. 3. Files or Script translator wants to perform non-general documents. EPerm1. The process is in tracking mode, the executor does not have root privileges, and the file to be executed has a SUID or SGID bit. 2. The file system to which the file to be performed is hung in the Nosuid mode, and the file to be executed has a SUID or SGID bit, but the executor does not have root privileges. E2BIG parameter arrays Excessive Enoexec Unable to determine the execution file format of the file, it is possible to format errors or cannot be executed on this platform. The string address referred to in the EFault parameter filename is exceeded. The character string referred to in the enametoolong parameter filename is too long. ENOent parameter filename string does not exist. Enoaddir Core Insufficient ENOTDIR Parameters FileName Strings The directory path included is not a valid directory EACCES Parameter FileName string contains the directory paths that cannot be accessed, and the permissions are not eLoop excessive symbols Connection ETXTBUSY files have been opened by other processes. Write data into this file EIO I / O Acquiors ENFILE has reached the total number of open files allowed by the system. Emfile has reached the total number of files that the system allows the single process to be opened. EINVAL wants to perform files ELF execution format Not only one PT_INTERP section EISDIR ELF translator is a problem with a directory Elibbad ELF translator. example

#include main () {char * argv [] = {"ls", "- al", "/ etc / passwd", (char *) 0}; char * envp [] = {"Path = / bin ", 0} execve (" / bin / ls ", argv, envp);

carried out

-rw-r - r - 1 root root 705 Sep 3 13: 52 / etc / passwd

EXECVP (executable)

related functions

Fork, Execl, Execle, Execlp, Execv, Execve

Header file

#include

Definition function

INT EXECVP (Const Char * file, char * const argv []);

Function description

Execvp () will find the file name that meets the parameter file from the directory referred to in the PATH environment variable, and then execute the file, and then pass the second parameter Argv to the file you want to execute.

return value

If the function does not return, the function will not return, and the execution failed, returned to -1, and the cause is existed in Errno.

error code

Please refer to Execve ().

example

/ * Please contact Execlp () Examples * / # include main () {char * argv [= {"ls", "- al", "/ etc / passwd", 0}; EXECVP ( "Ls", argv);

carried out

-rw-r - r - 1 root root 705 Sep 3 13: 52 / etc / passwd

EXIT (normal end process)

related functions

_exit, atexit, on_exit

Header file

#include

Definition function

Void exit; Int status;

Function description

EXIT () is used to end the execution of the current process and return the parameter status to the parent process, and all the buffer data of the process will automatically write back and close the unstable file.

return value

example

Refer to WAIT ()

_

EXIT (End Process)

related functions

EXIT, WAIT, ABORT header file

#include

Definition function

Void_exit (int stat);

Function description

_exit () is used to immediately end the execution of the current process and return the parameters status to the parent process and turn off the unstoped file. This function is called and will not return and will pass the SIGCHLD signal to the parent process, the parent process can be ended by the WAIT function to end the child process.

return value

Additional information

_exit () does not process standard I / O buffers, please use exit () if you want to update buffers.

VFORK (create a new process)

related functions

Wait, Execve

Header file

#include

Definition function

PID_T VFORK (Void);

Function description

vFork () will generate a new child process, and its child process copies the data and stack space of the parent process, and inherits the user code of the Parent process, the group code, environment variable, the open file code, the working directory, and resource restrictions, etc. . Linux uses the Copy-On-Write (COW) technology only when one of the processes attempts to modify the space you want to copy, because these inheritance information is copied, it does not refer to the same memory space, so The child process is modified and the parent process for these variables will not synchronize. In addition, the child process does not inherit the file lock and untreated signals of the Parent process. Note that Linux does not guarantee that the child process will execute or execute before the parent process, so pay attention to writing a program.

The occurrence of deadlocks or competitive conditions.

return value

If VFORK () successs, the parent process returns a newly established sub-process code (PID), and 0 is returned in the newly established child process. If the VFORK fails, it returns to -1 and the cause is existed in Errno.

error code

Eagain is insufficient. EnomeM is insufficient and cannot be configured with the data structure space required for the core.

example

#include main () {if (vFork () = = 0) {Printf ("this is the child process / n");} else {printf ("this is the parent process / n"); }

carried out

this is the parent processthis is the child process

getPgID (acquired process group identification code)

related functions

Setpgid, setpgrp, getpgrp

Header file

#include

Definition function

PID_T getpgid (PID_T PID);

Function description

getpgID () is used to obtain the group codes to which the parameter PID specifies the process. If the parameter PID is 0, it will acquire the code code for the current process.

return value

If the execution is successful, the group identification code is returned. If there is an error, it returns -1, the error is existed in Errno.

error code

Esrch does not find the process that meets the parameter PID specified.

example

/ * Nomination code for acquiring the init process (PID = 1) * / # include mian () {printf ("init GID =% D / N", getpgid (1));}

carried out

INIT GID = 0

getPgrp (acquired process group identification code)

related functions

Setpgid, getpgid, getpgrp

Header file

#include

Definition function

PID_T getpgrp (void);

Function description

getPgrp () is used to get the unconssed code to which the current process belongs. This function is equivalent to calling getpgid (0); return value

Returns the unconssed code to which the current process belongs.

example

#include main () {printf ("My GID =% D / N", getPgrp ());}

carried out

my gid = 29546

getPID (get a process identification code)

related functions

Fork, kill, getpid

Header file

#include

Definition function

PID_T getpid (void);

Function description

getPID () is used to get the process identification code of the current process, and many programs use this value to establish temporary files to avoid the issues that are the same as temporary files.

return value

Current process identification code

example

#include main () {printf ("pID =% d / n", getpid ());}

carried out

PID = 1494 / * is not necessarily the same for each execution result * /

Getppid (get the process identification code for the parent process)

related functions

Fork, kill, getpid

Header file

#include

Definition function

PID_T getppid (void);

Function description

getppid () is used to obtain the parent process identification code for the current process.

return value

The parent process identification code for the current process.

example

#include main () {printf ("My Parent 'PID =% D / N", getppid ());}

carried out

My Parent PID = 463

GetPriority (get priority to program process)

related functions

SetPriority, Nice

Header file

#include #include

Definition function

Int getPriority (int WHICH, INT WHO);

Function description

getPriority () can be used to achieve processes, process groups, and user processes to perform priority.

parameter

Which has three values. The parameter who has different definitions of WHICH WHO representative. Between, representing the priority of the process, the lower the value, the lower the representative has a high priority, and the execution will be more frequent.

return value

Returns the process to perform priority, if there is an error, the return value is -1 and the error is existed in Errno.

Additional information

Since the return value is likely to be -1, it is necessary to check if Errno has an error reason. It is best to clear the errno variable before calling the subunpection.

error code

The Esrch parameter which or WHO may be wrong, but can't find a conformity process. EINVAL parameter which value error.

NICE (change process priority order)

related functions

SetPriority, getPriority

Header file

#include

Definition function

INT Nice (int INC);

Function description

Nice () used to change the process of the process to perform priority. The larger the value of the parameter INC, the more the sequence is ranked, that is, the slower the process will be executed. Only super users can use a negative INC value, representing priority order, the process will be faster.

return value

If the execution is successful, it returns 0, otherwise returns -1, and the cause is existed in Errno.

error code

Eperm General user attempts to transfer the negative parameter INC value change process priority.

ON_EXIT (Set the function called before the program is ended)

related functions

_EXIT, ATEXIT, EXIT

Header file

#include

Definition function

INT ON_EXIT (Void (INT, VOID *), VOID * ARG);

Function description

ON_EXIT () is used to set the function called before the program is ended. When the program returns exit () or returning from the main, the function specified by the parameter function will be called first, and then the program is actually ended by the exit (). The parameter arg pointer will pass to the parameter function function, please see the examples for details.

return value

If the execution is successful, it returns 0, otherwise returns -1, and the cause is existed in Errno.

Additional information

example

#include void my_exit (int stat ") {Printf (" Before exit ()! / n "); Printf (" exit (% d) / n ", status; printf (" arg =% S / N ", (char *) arg);} main () {char * str =" test "; ON_EXIT (my_exit, (void *) str); exit (1234);}

carried out

Before exit ()! EXIT (1234) arg = TEST

SetPGID (Setup Process Group Identification Code)

related functions

getpgid, setpgrp, getpgrp

Header file

#include

Definition function

INT setpgid (PID_T PID, PID_T PGID);

Function description

setpgid () Set the group identification code to which the parameter PID specified process belongs to the group code specified by the parameter PGID. If the parameter PID is 0, it will be used to set the code code of the current process. If the parameter PGID is 0, it will be replaced by the process identification code of the current process.

return value

If the execution is successful, the group identification code is returned. If there is an error, it returns -1, the error is existed in Errno.

error code

Einval parameter PGID is less than 0. The EPERM process is not enough, and the call cannot be completed. Esrch does not find the process that meets the parameter PID specified.

SetPGRP (Setup Process Group Identification Code)

related functions

Getpgid, setpgid, getpgrp

Header file

#include

Definition function

Int setPgrp (void);

Function description

setpgrp () Sets the group identification code to which the current process belongs is the process identification code of the current process. This function is equivalent to calling setpgid (0, 0).

return value

If the execution is successful, the group identification code is returned. If there is an error, it returns -1, the error is existed in Errno.

SetPriority (Setup program process execution priority)

related functions

GetPriority, Nice

Header file

#include #include

Definition function

INT setPriority (int which, int who, int prio);

Function description

SetPriority () can be used to set up processes, process groups, and user processes to perform priority. The parameter which has three values. The parameter who is based on the which value. The meaning of the meaning of the Which WHO represents the meaning of the process identification code prio_pgrp who as the process of the process of the process. PRIO_USER WHO is the user identification code parameter PRIO is between -20 to 20 . Representing the progress of the process, the lower the value, the lower the representative has a high priority, and the execution will be more frequent. This priority is 0, and only superusers (root) allow this value to be reduced. return value

If the execution is successful, it returns 0. If there is an error, the return value is -1, the error is existed in Errno. The Esrch parameter which or the WHO may be wrong, and if you can't find the EINVAL parameter which value. Eperm permissions are not enough, unable to complete settings Eacces General users cannot reduce priority

SYSTEM (execute shell command)

related functions

Fork, Execve, Waitpid, Popen

Header file

#include

Definition function

Int system (const char * string);

Function description

System () will call the fork () generated sub-process, and the sub-process calls / bin / sh-c string to execute the command represented by the parameter String string, and this command is immediately returned to the processes of the original call. The SIGINT and SIGQUIT signals are ignored during the call system () period.

return value

Returns 127 if system () fails when calling / bin / sh, and other failure reasons return -1. If the parameter string is an empty pointer (NULL), the non-zero value is returned. If the system () call success, finally returns the return value after executing the shell command, but this return value may also be returned to the system () call / bin / sh failed, so it is best to check Errno to confirm the execution success. .

Additional information

Do not use System () when writing a program with Suid / SGID permissions, system () will inherit environment variables, which may cause system security issues through environmental variables.

example

#include main () {system ("ls -al / etc / passwd / etc / shadow");}

carried out

-rw-r - r - r - 1 root root 705 Sep 3 13: 52 / etc / passwd-r --------- 1 root root 572 Sep 2 15: 34 / etc / shadow

Wait (waiting for the child process interrupt or end)

related functions

Waitpid, Fork

Header file

#include #include

Definition function

PID_T WAIT (INT * STATUS);

Function description

Wait () will temporarily stop the current execution until there is a signal to come to the end of the child. If the child process has ended in calling Wait (), Wait () will immediately return the sub-process end status value. The end status value of the child process is returned by the parameter status, while the process identification code of the child process will return. If you don't care about the status value, then

parameter

Status can be set to NULL. Please refer to WaitPid () for the end status value of the child process.

return value

If you perform success, the sub-process identification code (PID) is returned if there is an error occurs. Failure caused in Errno.

Additional information

example

#include #include #include #include main () {pid_t pid; int status, i; if (fork () = = 0) {PrintF ("this is the child process .pid =% D / N", getPID ()); exit (5);} else {Sleep (1); Printf ("this is the parent process, wait for Child ... / n "; PID = Wait (& status); I = WexitStatus (status); Printf (" Child's PID =% D .Exit Status = ^ D / N ", PID, I);}}

This is the child process.pid = 1501this is the parent process .wait for child ... child's pid = 1501, exit status = 5

Waitpid (waiting for the child process to be interrupted or end)

related functions

Wait, fork

Header file

#include #include

Definition function

PID_T WAITPID (PID_T PID, INT * STATUS, INT OPTIONS);

Function description

WaitPid () will temporarily stop the current process until there is a signal to come or the child process. If the child process has ended in calling Wait (), Wait () will immediately return the sub-process end status value. The end status value of the child process is returned by the parameter status, while the process identification code of the child process will return. If the status value is not completed, the parameter status can be set to null. The parameter PID is a child process identification code to wait, and the other value is as follows: PID <1 Wait for the process group identifies any sub-process of the PID absolute value. PID = -1 Wait for any sub-process, equivalent to Wait (). PID = 0 Wait for the process group identification code to any childhood that is the same as the current process. PID> 0 Waiting for any child process identification code as a child process. Parameter Option can be 0 or below or combined WNOHANG if there is no ended child process, it will return immediately, and will not wait. Wuntraced If the child process enters the suspension of execution, it will return immediately, but the end status is not allowed. The end state of the child process returns to Status, and there are several macros to discriminate the end case WifeXITED (Status) If the child process is ended, it is a non-0 value. WexitStatus (status) acquisitions the end code returned by the child process (), which generally uses WifeXITED to determine if it is normal to use this macro. WiFSignaled (Status) If the child process is over because the signal is over, this macro value is true Wtermsig (STATUS) acquiring the signal code that is aborted by the signal due to the signal, which generally uses WiFSignaled to determine this macro. WiFstopped (status) If the child process is suspended, this macro value is true. This is generally only available when using wuntraced. Wstopsig (status) gets the signal code for the initiation of the sub-process, which generally uses WiFstopped to determine this macro.

return value

If you perform success, the sub-process identification code (PID) is returned if there is an error occurs. Failure caused in Errno.

example

Refer to Wait ().

FPRINTF (formatted output data to file)

related functions

Printf, fscanf, vfprintf

Header file

#include

Definition function

INT fprintf (file * stream, const char * format, .....); function description

FPRINTF () will be converted and formatted according to the parameter Format string, and then output the result to the file specified by the parameter stream until the string ends ('/ 0').

return value

For the format of the parameter Format string, please refer to Printf (). Success returns the number of characters actually output, and the failure returns -1, and the error is existed in Errno.

example

#include main () {INT i = 150; int J = -100; Double K = 3.14159; FPrintf (stdout, "% D% f% x / n", J, k, i); fprintf (stdout, "% 2D% * D / N", I, 2, i);}

carried out

-100 3.141590 96150 150

Fscanf (formatted string input)

related functions

Scanf, SSCANF

Header file

#include

Definition function

INT fscanf (file * stream, const char * format, ....);

Function description

FSCANF () reads a string in the file stream of the parameter stream, and then converts and formats the data according to the parameter format string. Please refer to Scanf () in the form of format conversion. The converted structure exists in the corresponding parameters.

return value

Success returns the number of parameters, and the failure returns -1, and the error is existed in Errno.

Additional information

example

#include main () {INT i; unsigned int j; char s [5]; fscanf (stdin, "% D% x% 5 [AZ]% * S% f", & i, & j, s , s); Printf ("% D% D% S / N", I, J, S);}

carried out

10 0x1b aaaaaaaa Bbbbbbbbb / * Enter * / 10 27 aaaaa from the keyboard

Printf (Format Output Data)

related functions

Scanf, Snprintf

Header file

#include

Definition function

INT Printf (const char * format, ...........);

Function description

Printf () converts and formats data according to the parameter Format string, and then writes the result to the standard output device until the string ends ('/ 0'). Parameters Format strings can contain the following three character types 1. General text, accompanied by direct output. 2.ascii control character, such as / t, / n, etc. 3. Format conversion characters. The format is converted into a percentage symbol (%) and its subsequent format characters. In general, each% symbols must have a printf () parameter with the echo (only when the %% conversion character occurs), and the data type to output must correspond to it. The conversion character type is the same. The general form of Printf () format transitions is the following parameters enclosed in parentheses, and% and TYPE are necessary. Introduce the parameters of several form integer% D integers of Type first, will be converted into a symbolic decimal number% u integer parameter to be converted to an unsigned decimal number% O integer parameter parameters will be converted to one The parameter of the octal number% x integer will be converted into a symbolic hexadecimal number, and the parameters of the% X integer will be converted to a symbolic hexadecimal number with uppercase. ABCDEF indicates that the floating-point type% F Double type parameter is turned into a decimal number and takes six points below the decimal point, four rounds. The% e Double type parameter is printed in the form of an index. There is a number before the decimal point, and the six digits will be represented by the index portion at lowercase. % E is the same with% E, the only difference is that the index portion will be represented by uppercase. The% g Double type parameter automatically selects the format of% f or% e to print, and its standard is determined based on the value of the value and the set valid bits. % G is the same as% G, the only difference is to select% E format when printing in an index. Characters and string% C integer parameters are transferred to unsigned char types. % S The parameter of the string will be outputted by word until the NULL character is that the% P is if the parameter is the "Void *" pointer to display the hexadecimal format. PREC has several cases 1. The minimum number of positive integers. 2. Represents the number of decimal digits in the floating-point type 3. The maximum value of the significant bits in% G format. 4. The maximum length of the string in% S format. 5. If × symbols, the next parameter value is the maximum length. Width is the minimum length of the parameter. If this column is not a value, but * symbol, the following parameters are as a parameter length. Flags has the following cases #name? When printing negative, printf () will print a negative, and the integer does not add any negative. This flag will make one positive number ( ) before the print positive. # This flag will have different meanings depending on its subsequent conversion characters. When the type O is previous (as% # O), one O will be printed before the printed eight-based value. Before the type is X (% # x), you will be printed in the printed hexadecimal number of '0x', which will force the numerical print decimal point before the type E, E, F, G or G. When the type g or g is, the decimal point and the number of decimal bits are retained. 0 When there is a specified parameter, no numbers will be added to 0. The default is to turn off this flag, so a blank character will generally print. return value

Success returns the number of characters actually output, and the failure returns -1, and the error is existed in Errno.

example

#include main () {INT i = 150; int J = -100; Double K = 3.14159; Printf ("% D% f% x / n", J, k, i); Printf (" % 2D% * D / N ", I, 2, i); / * Parameter 2 will be in format *, and the% 2D agreement * /}

-100 3.14159 96150 150

SACNF (formatted string input)

related functions

Fscanf, Snprintf

Header file

#include

Definition function

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

Function description

ScanF () converts the input data to the parameter format string to convert and format the data. The general form of SCANF () format conversion is as follows [*] [size] [l] [h] Type encloses parameters enclosed in parentheses as selective parameters, and% and TYPE are necessary. * The corresponding parameter data is ignored is not saved. Size is the length of the data that allows parameters. l The data value entered is saved in long int or double. The data value of H is saved in Short INT. Introducing several form% D input of Type, which is converted into a symbolic decimal number (int). % I entered by the data will be converted to a symbolic decimal number. If the input data is converted to the hex number of hexadecimal numbers in "0x" or "0x", if the beginning of "0" is turned to convert the octal number, other cases represent Decoction. % 0 The data entered by the% 0 will be converted into an unsigned octal number. % U The data entered will be converted into a symbolic positive integer. % X Entered by the data is unsigned hexadecimal number, and the converted INT variable is exemplified. % X The same% x% F input data is a symbolic floating point type, and the conversion is converted to the Float type variable. % E% f% e with the same% f% g of the same% F% S input data is a string with space characters as termination. % C input data is a single character. [] Read data but only characters in parentheses are allowed. Such as [A-Z]. [^] The characters after reading the data but not allowing the ^ symbols of the brackets, such as [^ 0-9].

return value

Success returns the number of parameters, and the failure returns -1, and the error is existed in Errno.

example

#include main () {INT i; unsigned int j; char s [5]; scanf ("% D% x% 5 [AZ]% * S% f", & i, & j, s, s PRINTF ("% D% D% S / N", I, J, S);}

carried out

10 0x1b aaaaaaaaaa Bbbbbbbbb10 27 AAAAA

Sprintf (formatted string replication)

related functions

Printf, Sprintf

Header file

#include

Definition function

INT Sprintf (Char * Str, Const Char * Format, .......);

Function description

Sprintf () converts and formats data according to the parameter Format string, then copy the result to the array array of parameter STR until the string ends ('/ 0'). For the format of the parameter Format string, please refer to Printf ().

return value

Success returns the length of the parameter STR string, and the failure returns -1 and the error is existed in Errno.

Additional information

Use this function to pay attention to stack overflow, or use Snprintf ().

example

#include main () {char * a = "this is string a!"; char buf [80]; sprintf (buf, ">>>% s <<< / n", a); printf ("% S" .buf);

>>> Is String a! <<<

SSCANF (formatted string input)

related functions

Scanf, Fscanf

Header file

#include

Definition function

INT SSCANF (const char * str, const char * format, ........);

Function description

SSCANF () converts the string of the parameter STR to the parameter format string to convert and format the data. Please refer to Scanf () in the form of format conversion. The resulting result is stored in the corresponding parameters.

return value

Success returns the number of parameters, and the failure returns -1, and the error is existed in Errno.

example

#include main () {INT i; unsigned int j; char input [] = "10 0x1b aaaaaaa bbbbbbbbbbb"; char s [5]; SSCANF (Input, "% D% x% 5 [AZ] % * S% f ", & I, & J, S, S); Printf ("% D% D% S / N ", I, J, S);}

carried out

10 27 AAAAA

Vfprintf (formatted output data to file)

related functions

Printf, fscanf, fprintf

Header file

#include #include

Definition function

Int Vfprintf (file * stream, const char * format, va_list ap);

Function description

Vfprintf () will be converted and formatted according to the parameter Format string, and then output the result to the file specified by the parameter stream until the string ends ('/ 0'). For the format of the parameter Format string, please refer to Printf (). VA_LIST Usage Please refer to Appendix C or vprintf () example.

return value

Success returns the number of characters actually output, and the failure returns -1, and the error is existed in Errno.

example

Refer to FPRINTF () and Vprintf ().

Vfscanf (formatted string input)

related functions

Scanf, SSCANF, FSCANF

Header file

#include

Definition function

Int vfscanf (file * stream, const char * format, va_list AP);

Function description

vfscanf () reads the string in the file stream of the parameter stream, and then converts and formats the data according to the parameter format string. Please refer to Scanf () in the form of format conversion. The resulting result is stored in the corresponding parameters. Please refer to Appendix C or vprintf ().

return value

Success returns the number of parameters, and the failure returns -1, and the error is existed in Errno.

example

Refer to FSCANF () and Vprintf ().

Vprintf (formatted output data)

related functions

Printf, vfprintf, vsprintf

Header file

#include #include

Definition function

Int vprintf (const char * format, va_list AP);

Function description

Vprintf () effects and printf (), the parameter format format is the same. VA_LIST is a parameter column, usage, and examples of the number, please refer to Appendix C. return value

Success returns the number of characters actually output, and the failure returns -1, and the error is existed in Errno.

example

#include #include int my_printf (const char * format, ...) {va_list ap; int RetVal; Va_start (AP, FORMAT); Printf ("My_Printf ():"); RetVal = Vprintf (Format, AP); VA_END (AP); Return RetVal;} main () {INT i = 150, J = -100; Double K = 3.14159; My_Printf ("% D% f% x / n", J , K, I); MY_PRINTF ("% 2D% * D / N", I, 2, i);}

carried out

MY_PRINTF (): -100 3.14159 96my_printf (): 150 150

Vscanf (formatted string input)

related functions

vsscanf, vfscanf

Header file

#include #include

Definition function

Int vscanf (const char * format, va_list AP);

Function description

vscanf () converts the input data to the parameter format string to convert and format the data. Please refer to Scanf () in the form of format conversion. The resulting result is stored in the corresponding parameters. VA_LIST Usage Please refer to Appendix C or vprintf () example.

return value

Success returns the number of parameters, and the failure returns -1, and the error is existed in Errno.

example

Please refer to Scanf () and Vprintf ().

vsprintf (formatted string replication)

related functions

VNSPrintf, vprintf, snprintf

Header file

#include

Definition function

INT vsprintf (char * str, const char * format, va_list ap);

Function description

vSprintf () converts and formats data based on the parameter format string, then copy the result to the array array of parameter STR, until the string ends ('/ 0') appears. For the format of the parameter Format string, please refer to Printf (). VA_LIST Usage Please refer to Appendix C or vprintf () example.

return value

Success returns the length of the parameter STR string, and the failure returns -1 and the error is existed in Errno.

example

Please refer to vprintf () and vsprintf ().

Vsscanf (formatted string input)

related functions

vscanf, vfscanf

Header file

#include

Definition function

INT Vsscanf (const char * str, const char * format, va_list ap);

Function description

Vsscanf () converts the string of the parameter STR to convert and format the data according to the parameter format string. Please refer to Appendix C or vprintf () examples in the form of a format conversion.

return value

Success returns the number of parameters, and the failure returns -1, and the error is existed in Errno.

example

Please refer to SSCANF () and Vprintf ().

Access (determined if there is access to access file)

related functions

Stat, Open, Chmod, Chown, SetUID, Setgid

Header file

#include Definition function

INT Access (const char * pathname, int mode);

Function description

Access () will check if you can read / write an existing file. Several cases of parameter modes, R_OK, W_OK, X_OK, and F_OK. R_OK, W_OK and X_OK are used to check if the file has permission to read, write, and execute. F_ok is used to determine if the file exists. Since Access () is only permissible verification, it is ignored that the file form or file content, so if a directory is "writable", it means that you can create new files in this directory, not this directory. It is treated as a file. For example, you will find that DOS files have "executable" permissions, but it will fail with Execve ().

return value

If all the permissions of all desired nuclear returns 0 values, it returns to -1 as long as one permission is disabled.

error code

The EACcess parameter Pathname specified by the file does not meet the permissions of the required test. Erofs wants to test files that write authorities exist within read-only file systems. The EFAULT parameter Pathname pointer exceeds the accessible memory space. The EINVAL parameter mode is incorrect. ENAMETOOLONG parameter Pathname is too long. Enotdir parameter pathname is a directory. The ENOMEM core is not enough ELOOP parameter pathname has excessive symbolic connection issues. EIO I / O Access error.

Additional information

The judgment of using Access () to operate is especially careful, for example, in Access (), the open () empty file may cause system security issues.

example

/ * Judgment whether to read / etc / passwd * / # include int main () {ix ("/ etc / passwd", r_ok) = = 0) Printf ("/ etc / passwd can Be read / n ");

carried out

/ etc / passwd can be ready

Alphasort (sorted by alphabetical order)

related functions

Scandir, QSORT

Header file

#include

Definition function

Int alphasort (const struct Dirent ** b);

Function description

AlphaSort () is transmitted to QSort () as a function of QSORT () for Scandir (), for details, please refer to Scandir () and QSort ().

return value

Refer to QSORT ().

example

/ * All directory structures under the read / directory, and arrange * / main () {struct Dirent ** Namelist; int i, total; total = scandir ("/", & namelist, 0, alphasort); if (Total <0) PERROR ("scandir"); else {for (i = 0; i D_NAME); Printf ("Total =% D / N ", Total);}}

carried out

... gnome.gnome_privateerrorlogweblogbinbootdevdoscdosdetchomeliblost FoundMiscmNToptProcrootsbintmpusrvartotal = 24

CHDIR (Change the current work (directory)

related functions

Getcwd, chroot

Header file

#include

Definition function

INT ChDIR (const char * path); function description

CHDIR () is used to change the current working directory to the directory referred to in parameter PATH.

return value

Returns 0, fail back -1, errno is the error code.

example

#include main () {chdir ("/ tmp"); Printf ("Current Working Directory: S / N", getCwd (null, null);}

carried out

Current Working Directory: / TMP

CHMOD (change file permission)

related functions

FCHMOD, Stat, Open, Chown

Header file

#include #include

Definition function

Int chmod (const char * path, mode_t mode);

Function description

CHMOD () will change the permissions of the parameter PATH specified file according to the parameter MODE permission.

parameter

The Mode has the following several combined S_ISUID 04000 files (SET Group-id ON Execution) bit S_ISGID 02000 file S_ISVTX 01000 file S_Ir (S_IREAD) 00400 file owner readable Permissions S_IWUSR (S_IWRITE) 00200 file owner can write permission s_ixusr (s_iexec) 00100 file owner's executable permission S_IRGRP 00040 user group readable permissions S_IWGRP 00020 user group can write access rights S_IXGRP 00010 user group Execution Permissions S_IROTH 00004 Other Users Read Permissions S_IWOTH 00002 Other Users Other Users S_IXOTH 00001 Other Users Other Permissions Only the owner or valid user identification code of the file is 0 to modify the file permission. Based on system security, if you want to write data to an executable file, the execution file has S_ISUID or S_ISGID permissions, the two bits will be cleared. If a directory has S_ISUID bit permissions, it indicates that only the owner or root of the file in this directory can delete the file.

Access (determined if there is access to access file)

related functions

Stat, Open, Chmod, Chown, SetUID, Setgid

Header file

#include

Definition function

INT Access (const char * pathname, int mode);

Function description

Access () will check if you can read / write an existing file. Several cases of parameter modes, R_OK, W_OK, X_OK, and F_OK. R_OK, W_OK and X_OK are used to check if the file has permission to read, write, and execute. F_ok is used to determine if the file exists. Since Access () is only permissible verification, it is ignored that the file form or file content, so if a directory is "writable", it means that you can create new files in this directory, not this directory. It is treated as a file. For example, you will find that DOS files have "executable" permissions, but it will fail with Execve ().

return value

If all the permissions of all desired nuclear returns 0 values, it returns to -1 as long as one permission is disabled.

error code

The EACcess parameter Pathname specified by the file does not meet the permissions of the required test. Erofs wants to test files that write authorities exist within read-only file systems. The EFAULT parameter Pathname pointer exceeds the accessible memory space. The EINVAL parameter mode is incorrect. ENAMETOOLONG parameter Pathname is too long. Enotdir parameter pathname is a directory. The ENOMEM core is not enough ELOOP parameter pathname has excessive symbolic connection issues. EIO I / O Access error. Additional information

The judgment of using Access () to operate is especially careful, for example, in Access (), the open () empty file may cause system security issues.

example

/ * Judgment whether to read / etc / passwd * / # include int main () {ix ("/ etc / passwd", r_ok) = = 0) Printf ("/ etc / passwd can Be read / n ");

carried out

/ etc / passwd can be ready

Alphasort (sorted by alphabetical order)

related functions

Scandir, QSORT

Header file

#include

Definition function

Int alphasort (const struct Dirent ** b);

Function description

AlphaSort () is transmitted to QSort () as a function of QSORT () for Scandir (), for details, please refer to Scandir () and QSort ().

return value

Refer to QSORT ().

example

/ * All directory structures under the read / directory, and arrange * / main () {struct Dirent ** Namelist; int i, total; total = scandir ("/", & namelist, 0, alphasort); if (Total <0) PERROR ("scandir"); else {for (i = 0; i D_NAME); Printf ("Total =% D / N ", Total);}}

carried out

... gnome.gnome_privateerrorlogweblogbinbootdevdoscdosdetchomeliblost FoundMiscmNToptProcrootsbintmpusrvartotal = 24

CHDIR (Change the current work (directory)

related functions

Getcwd, chroot

Header file

#include

Definition function

INT ChDIR (Const Char * PATH);

Function description

CHDIR () is used to change the current working directory to the directory referred to in parameter PATH.

return value

Returns 0, fail back -1, errno is the error code.

example

#include main () {chdir ("/ tmp"); Printf ("Current Working Directory: S / N", getCwd (null, null);}

carried out

Current Working Directory: / TMP

CHMOD (change file permission)

related functions

FCHMOD, Stat, Open, Chown

Header file

#include #include

Definition function

Int chmod (const char * path, mode_t mode);

Function description

CHMOD () will change the permissions of the parameter PATH specified file according to the parameter MODE permission. parameter

The Mode has the following several combined S_ISUID 04000 files (SET Group-id ON Execution) bit S_ISGID 02000 file S_ISVTX 01000 file S_Ir (S_IREAD) 00400 file owner readable Permissions S_IWUSR (S_IWRITE) 00200 file owner can write permission s_ixusr (s_iexec) 00100 file owner's executable permission S_IRGRP 00040 user group readable permissions S_IWGRP 00020 user group can write access rights S_IXGRP 00010 user group Execution Permissions S_IROTH 00004 Other Users Read Permissions S_IWOTH 00002 Other Users Other Users S_IXOTH 00001 Other Users Other Permissions Only the owner or valid user identification code of the file is 0 to modify the file permission. Based on system security, if you want to write data to an executable file, the execution file has S_ISUID or S_ISGID permissions, the two bits will be cleared. If a directory has S_ISUID bit permissions, it indicates that only the owner or root of the file in this directory can delete the file.

return value

Permission changes have successfully returned 0, failed to return -1, and the error is existed in Errno.

error code

Eperm process's valid user identification code is different from file owners who want to modify their permissions, and nor root privileges. The file specified by the EACcess parameter PATH cannot be accessed. Erofs wants to write to the permissions to exist within the read-only file system. The Efault parameter PATH pointer exceeds the accessible memory space. ENVAL parameter MODE incorrect Enametoolong Parameter Path Too long enphotd specified files There is no enotdir parameter Path path is not a directory ENOMEM core memory instead of ELOOP parameter PATH has too many symbolic connection issues. EIO I / O Acquisition Error

example

/ * Set / etc / passwd file permissions to S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH> #include #include main () {chmod ("/ etc / passwd" , S_irusr | s_iwusr | s_irgrp | s_iroth;}

Chown (change the owner of the file)

related functions

FChown, LChown, Chmod

Header file

#include #include

Definition function

INT Chown (const char * path, uid_t owner, gid_t group);

Function description

Chown () will change the owner of the parameter PATH to the user representative of the parameter OWNER, and the group of the file is more parameter group group. If the parameter OWNER or group is -1, the corresponding owner or group will not change. All root and file owners can change the file group, but the owner must be a member of the parameter group group. When the root changes the file owner or group with chown (), the file is cleared if the file has S_ISUID or S_ISGID permissions, and if there is S_IxGID permissions but not the S_IXGRP bit, the file will be forced to lock, file mode Will retain.

return value

Success returns 0, failed to return -1, and the error is existed in Errno.

error code

Refer to chmod ().

example

/ * Set the owner and group of / etc / passwd all set to root * / # include #include main () {chown ("/ etc / passwd", 0,0 ); chroot (change root directory)

related functions

chdir

Header file

#include

Definition function

INT Chroot (const char * path);

Function description

Chroot () is used to change the root directory as the directory specified by the parameter PATH. Only super users allow changing the root directory, the child process will inherit the new root directory.

return value

When the call is successful, it returns 0, and the failed is returned to -1, and the error code exists in Errno.

error code

Eperm privilege is not possible to change the root directory. The Efault parameter PATH pointer exceeds the accessible memory space. ENAMETOOLONG parameter PATH is too long. The directory in the EnotDir path exists but is not a real directory. The EACcess is rejected when the cordial memory is insufficient. The ELOOP parameter PATH has too many symbolic connection issues. EIO I / O Access error.

example

/ * Change the root directory to / TMP and switch the working directory to / tmp * / # include main () {chroot ("/ tmp"); chDIR ("/");}

CloseDir (turn off the directory)

related functions

OpenDir

Header file

#include #include

Definition function

INT CloseDir (Dir * Dir);

Function description

CloseDir () Close the directory stream referred to in the parameter DIR.

return value

When the shutdown is successful, it returns 0, the failure returns -1, the error is existed in Errno.

error code

Ebadf parameter DIR is invalid to directory flow

example

Refer to readir ().

FCHDIR (change the current work directory)

related functions

Getcwd, chroot

Header file

#include

Definition function

INT FCHDIR (INT FD);

Function description

FCHDIR () is used to change the current work directory into file descriptors referred to as parameter fd.

Return value

Return to 0, the failure returns -1, errno is the error code.

Additional information

example

#include #include #include #include main () {int fd; fd = open ("/ tmp", o_rdonly) FCHDIR (FD); Printf ("Current Working Directory:% S / N", GetCwd (NULL, NULL); Close (FD);}

carried out

Current Working Directory: / TMP

FCHMOD (Permissions to change the file)

related functions

CHMOD, Stat, Open, Chown

Header file

#include #include

Definition function

INT FCHMOD (int Fildes, Mode_t Mode);

Function description

Fchmod () will change the permissions of the files nortified by the parameter Fildes according to the parameter MODE permissions. Parameters Fildes are file descriptors that have been opened. Please refer to chmod ().

return value

Returning 0, returns -1, the error is stored in Errno.

wrong reason

Ebadf Parameters Fildes are invalid file descriptors. Eperm process's valid user identification code is different from file owners who want to modify the permissions, and nor root privileges. Erofs wants to write to the permissions to exist within the read-only file system. EIO I / O Access error. example

#include #include main () {int fd; fd = open ("/ etc / passwd", o_rdonly); FCHMOD (FD, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); Close (fd);}

FChown (the owner of the file)

related functions

Chown, LChown, Chmod

Header file

#include #include

Definition function

INT FCHOWN (INT FD, UID_T OWNER, GID_T Group);

Function description

FCHOWN () will change the owner of the parameter FD to specify the file as the user representing the parameter Owner, and the group of the file is more than the group group. If the parameter Owner or Group is -1, the designer or group has changed. The parameter fd is the open file descriptor. When the root changes the file owner or group with FCHOWN (), this file will be cleared if you have S_ISUID or S_ISGID permissions.

return value

Success returns 0, and the failure returns -1, and the error is existed in Errno.

error code

Ebadf parameter fd file description word is invalid or the file is closed. Eperm process's valid user identification code is different from the file owner who wants to modify the permissions, and it does not have root privileges, or parameter Owner, Group is incorrect. Erofs wants to write files exist within read-only file systems. EIO I / O access error is not available in EIOnt specified file

example

#include #include #include main () {int fd; fd = open ("/ etc / passwd", o_rdonly); chown (fd, 0, 0); Close (FD);

FSTAT (file status by file description words)

related functions

Stat, Lserve, Chmod, Chown, Readlink, Utime

Header file

#include #include

Definition function

INT FSTAT (INT FILDES, STRUCT STAT * BUF);

Function description

FSTAT () is used to copy the file status referred to by the parameter Fildes into the structure referred to in the parameter BUF (Struct Stat). FSTAT () is identical to the stat () effect, and the different parameters are the file descriptors that have been opened. For details, please refer to Stat ().

return value

If the execution is successful, it returns 0, the failure returns -1, and the error code exists in Errno.

example

#include #include #include main () {struct statue; int fd; fd = open ("/ etc / passwd", o_rdonly); fstat FD, & BUF); Printf ("/ etc / passwd file size % d / n", buf.st_size;}

carried out

/ etc / passwd file size = 705

Ftruncate (change file size)

related functions

Open, Truncate

Header file

#include Definition function

INT FTRUNCATE (INT FD, OFF_T Length);

Function description

Ftruncate () change the file size specified by the parameter FD to the size specified by the parameter length. The parameter fd is the open file descriptor, and must be filed in a write mode. If the original file size is larger than the parameter length, the more than the part will be deleted.

return value

If the execution is successful, it returns 0, the failure returns -1, and the error is existed in Errno.

error code

Ebadf parameter fd file description word is invalid or the file is closed. The EINVAL parameter fd is a socket is not a file, or the file is not open in writing mode.

GetCwd (get the current work directory)

related functions

GET_CURRENT_DIR_NAME, GETWD, CHDIR

Header file

#include

Definition function

Char * getcwd (char * buf, size_t size);

Function description

GetCWD () copies the current working directory absolute path to the memory space referred to by the parameter BUF, and the parameter size is the space size of the BUF. When calling this function, the memory space referred to in BUF is large enough. If the string length of the working directory absolute path exceeds the parameter size size, the value null, the value of Errno is ERANGE. If the parameter buf is null, getCWD () automatically configures memory according to the size of the parameter size (using malloc ()), if the parameter size is also 0, the getCWD () will determine the degree of the string of the work directory absolute path. The memory size, the process can use free () to release this space after using this string.

return value

After success, copy the result to the memory space referred to in the parameter BUF, or return the auto-configured string pointer. Failure returns NULL, the error code is existed in Errno.

example

#include main () {char Buf [80]; getCwd (buf, sizeof (buf)); Printf ("Current Working Directory:% S / N", BUF);

carried out

Current Working Directory: / TMP

LINK (establish a file connection)

related functions

Symlink, unlink

Header file

#include

Definition function

INT LINK (Const Char * OldPath, Const Char * NewPath);

Function description

LINK () creates a new connection (hard connection) to the existing file specified by the parameter OldPath as specified by the name of the parameter newpath. If the name specified by the parameter newpath is not established.

return value

Success returns 0, failed to return -1, and the error is existed in Errno.

Additional information

The hard connection established by LINK () cannot span different file systems. If you need, please use SymLink ().

error code

The ExDev parameter OldPath and NewPath are not built in the same file system. Eperm Parameters OldPath and NewPath The file system referred to in NewPath does not support hard connection EROFS files exists in the read-only file system EFault parameter OldPath or NewPath pointer exceeds the accessible memory space. Enametollong Parameters OldPath or NewPath Too long EnomeM core memory instead EEXIST parameter NewPath refers to the file names already exist. The file referred to in the EMLINK parameter OldPath has reached the maximum number of connections. Eloop Parameters Pathname has excessive symbolic connection issues the remaining space of the ENOSPC file system. EIO I / O Access error.

example

/ * Establish / etc / passwd's hard connection to pass * / # include main () {link ("/ etc / passwd", "pass");} LSTAT (file status by file description word)

related functions

Stat, Fstat, Chmod, Chown, Readlink, Utime

Header file

#include #include

Definition function

INT LSTAT (Const Char * file_name.struct stat * buf);

Function description

LSTAT () is identical to the stat () effect, all of which acquire the file status referred to in parameter file_name, and the difference is that when the file is a symbolic connection, LSTAT () will return the status of the Link itself. For details, please refer to Stat ().

return value

If the execution is successful, it returns 0, the failure returns -1, and the error code exists in Errno.

example

Refer to STAT ().

OpenDir (Open Directory)

related functions

Open, Readdir, Closedir, Rewinddir, Seekdir, Telldir, Scandir

Header file

#include #include

Definition function

Dir * OpenDir (const char * name);

Function description

OpenDIR () is used to open the directory specified by the parameter name and return the DIR * Form of the directory stream, and Open () is similar to the next reading and search of the directory to use this return value.

return value

Success returns a directory stream of the DIR * type, returns NULL.

error code

EACCESS privileges The EMFILE has reached the number of files that can be opened at the same time. Enfile has reached the upper limit of the number of files that can be opened at the same time. Enotdir Parameters Name NAME NAME The specified directory does not exist, or the parameter Name is an empty string. EnomeM core is insufficient.

Readdir (read directory)

related functions

Open, OpenDir, Closedir, Rewinddir, Seekdir, Telldir, Scandir

Header file

#include #include

Definition function

Struct Dirent * Readdir (Dir * Dir);

Function description

ReadDir () Returns the next directory entry point of the parameter DIR directory stream. Structure dirent defined as follows struct dirent {ino_t d_ino; ff_t d_off; signed short int d_reclen; unsigned char d_type; har d_name [256;}; d_ino directory entry point inoded_off directory file at the beginning of this directory into the longitudinal displacement d_reclen _name point, The file type D_Name file name referred to without NULL character D_Type D_Name

return value

Success returns to the next directory entry point. Returns NULL if there is an error or read to the directory file.

Additional information

The eBadf parameter DIR is an invalid directory stream.

example

#include #include #include main () {DIR * DIR; Struct Dirent * Ptr; INT i; DIR = Opendir ("/ etc / rc.d "); While (PTR = readdir (dir))! = Null) {Printf (" D_NAME:% S / N ", PTR-> D_NAME);} CloseDir (DIR);}

d_name: .d_name: .. d_name: init.dd_name: rc0.dd_name: rc1.dd_name: rc2.dd_name: rc3.dd_name: rc4.dd_name: rc5.dd_name: rc6.dd_name: rcd_name: rc.locald_name: rc.sysinit

Readlink (acquired files referred to)

related functions

Stat, Lstat, Symlink

Header file

#include

Definition function

Int Readlink (const char * path, char * buf, size_t bufsiz);

Function description

ReadLink () will save the parameter PATH symbol connection content to the memory space referred to by the parameter BUF, and the return content is not ending with a NULL string, but returns the character number of the string. If the parameter bufsiz is less than the content length of the symbol connection, the excessive content will be truncated.

return value

Perform success, the file path string referred to by the symbol connection, the failure returns -1, the error code exists in Errno.

error code

Eaccess is rejected when the file is taken, the permissions are not enough EIINVAL parameter bufsiz is negative EIO I / O access error. Eloop wants to open with excessive symbolic connection issues. Enametoolong Parameter PATH Path Name Tap too long Enoent Parameters PATH The specified file does not exist in the EnOMem core memory instead of the eNOTDIR parameter Path path in the directory in the path, but is not a real directory.

REMOVE (delete file)

related functions

Link, rename, unlink

Header file

#include

Definition function

Int Remove (const char * pathname);

Function description

REMOVE () will delete the file specified by the parameter pathname. If the parameter PathName is a file, the unlink () process is called. If the parameter PathName is a directory, then RMDIR () is called. Please refer to UNLINK () and RMDir ().

return value

Success returns 0, and the failure returns -1, and the error is existed in Errno.

error code

Erofs wants to write files exists in the read-only file system EFault parameter Pathname pointer exceeds the accessible memory space Enametoolong parameter Pathname too long Enome core memory instead ELOOP parameter Pathname has too multi-symbolic connection problem EIO I / O Acquisition error.

Rename (change the file name or location)

related functions

Link, Unlink, Symlink

Header file

#include

Definition function

Int rename (const char * oldpath, const char * newpath);

Function description

Rename () will change the file name specified by the parameter OldPath to the file name indicated by the parameter newPath. If the file specified by NewPath already exists, it will be deleted.

return value

If the execution is successful, it returns 0, the failure returns -1, and the error is existed in Errno.

example

/ * Design a rename instruction under a DOS Rename old file name new file name * / # include void main (int argc, char ** argv) {if (argc <3) {printf ("Usage:% S OLD_NAME New_NAME / N ", Argv [0]); Return;} Printf ("% s =>% s ", argc [1], argv [2]); if (rename (Argv [1], Argv [2 ] <0) Printf ("error! / N"); ElsePrintf ("OK! / N");} REWINDDIR (Reset Reading Directory is starting)

related functions

Open, OpenDir, Closedir, Telldir, Seekdir, Readdir, Scandir

Header file

#include #include

Definition function

Void Rewinddir (Dir * Dir);

Function description

ReWindDir () is used to set the current read position of the parameter DIR directory stream as the original opening position.

return value

error code

Ebadf Dir is invalid to directory flow

example

#include #include #include main () {DIR * DIR; Struct Dirent * Ptr; DIR = OpenDir ("/ etc / rc.d"); While (PTR = ReadDir (Dir))! = null) {Printf ("D_NAME:% S / N", PTR-> D_NAME);} REWINDDIR (DIR); Printf ("Readdir Again! / N"); while ((ptr = readdir (dir))! = null) {printf ("D_NAME:% S / N", PTR-> D_NAME);} closedir (DIR);

carried out

d_name: .d_name: .. d_name: init.dd_name: rc0.dd_name: rc1.dd_name: rc2.dd_name: rc3.dd_name: rc4.dd_name: rc5.dd_name: rc6.dd_name: rcd_name: rc.locald_name: rc.sysinitreaddir again d_name:! .d_name: .. d_name: init.dd_name: rc0.dd_name: rc1.dd_name: rc2.dd_name: rc3.dd_name: rc4.dd_name: rc5.dd_name: rc6.dd_name: rcd_name: rc.locald_name: rc .sinit

Seekdir (Set the location of the reading directory)

related functions

Open, OpenDir, Closedir, Rewinddir, Telldir, Readdir, Scandir

Header file

#include

Definition function

Void seekdir (Dir * Dir, OFF_T OFFSET);

Function description

Seekdir () is used to set the current read position of the parameter DIR directory stream, and read it from this new location when calling readir (). Parameter OFFSET represents the offset at the beginning of the directory file.

return value

error code

Ebadf parameter DIR is invalid to directory flow

example

#include #include #include main () {DIR * DIR; STRUCT DIRENT * PTR; int offset, offset_5, i = 0; Dir = OpenDir (" /etc/rc.d" ";while((((((((ptr = readdir (dir))! = null) {offset = telldir (Dir); if ( i == 5) Offset_5 = Offset; Printf ("d_name:% S Offset:% D / N ", PTR-> D_NAME, OFFSET); SEEKDIR (Dir Offset_5); Printf (" ReadDir Again! / N "); While (Ptr = ReadDir (Dir))! = null) { OFFSET = TELLDIR (DIR); Printf ("D_NAME:% S Offset:% D / N", PTR-> D_Name.Offset);} CLOSEDIR (DIR);

D_name:. OFFSET: 12D_NAME: .. OFFSET: 24D_NAME: INIT.D Offset: 56d_name: rc1.d Offset: 72D_Name: rc2.d Offset: 88d_name: rc3.d Offset 104d_name: rc4.d Offset : 120d_name: rc5.d offset: 136d_name: rc6.d offset: 152d_name: rc offset 164d_name: rc.local offset: 180d_name: rc.sysinit offset: 4096readdir again d_name:! rc2.d offset: 88d_name: rc3.d offset 104d_name : rc4.d Offset: 120d_name: rc5.d Offset: 136d_name: rc6.d Offset: 152d_name: rc offset 164d_name: rc.local offset: 180D_name: rc.system Offset: 4096

Stat (get file status)

related functions

FSTAT, LSTAT, Chmod, Chown, Readlink, Utime

Header file

#include #include

Definition function

Int Stat (const char * file_name, struct stat * buf);

Function description

STAT () is used to copy the file status referred to by parameter file_name to the structure referred to in the parameter buf. Here is the description of the parameters in the struct status structure struct stat {dev_t st_dev; / * device * / ino_t ST_INO; / * Inode * / Mode_t ST_MODE; / * Protection * / NLINK_T ST_NLINK; / * NUMBER OF HARD LINKS * / UID_T ST_UID; / * user ID of owner * / gid_t st_gid; / * group ID of owner * / dev_t st_rdev; / * device type * / off_t st_size; / * total size, in bytes * / unsigned long st_blksize; / * blocksize for filesystem I / O * / unsigned long st_blocks; / * number of blocks allocated * / time_t st_atime; / * time of lastaccess * / time_t st_mtime; / * time of last modification * / time_t st_ctime; / * time of last change * /}; The I-NODEST_MODE file of the device number ST_INO file of the ST_DEV file is connected to the number of the hard connection of the file, and the file value of the original file is 1. The ST_UID file owner's user identification code ST_GID file owner's Uncam ST_RDEV If this file is a device file, the device number ST_SIZE file size is used to calculate the I / O buffer size of the ST_BLKSIZE file system. ST_BLCOKS occupies the number of file blocks, each block size of 512 bytes. The ST_AATIME file is only available for the time being accessed or executed. It is generally only changed when using MKNOD, UTIME, READ, WRITE and TRUCTATE.

The ST_MTIME file last changes time, generally only change the time that ST_CTIME I-NODE is changed in the last time with mknod, utime and write, this parameter is updated in the file owner, group, and permissions. st_mode description defines the following several cases S_IFMT 0170000 file type bit mask S_IFSOCK 0140000 scoketS_IFLNK 0120000 symbolic link file S_IFBLK 0060000 S_IFREG 0100000 general block directory means S_IFDIR 0040000 S_IFCHR 0020000 character means S_IFIFO 0010000 S_ISUID 04000 FIFO file ( SET User-id ON Execution) Bit S_ISGID 02000 file S_ISVTX 01000 file Sticky bit s_irusr (s_iread) 00400 file owner readable permission S_IWUSR (S_IWRITE) 00200 file owner Write permission s_ixusr (s_iexec) 00100 File All Act Implementation S_IRGRP 00040 User Pack Read Permissions S_IWGRP 00020 User Pack Writer S_IXGRP 00010 User Pack Excerpt S_Iroth 00004 Other User Ready Permissions S_IWOTH 00002 Other Users Write Permissions S_IXOTH 00001 Other Users Execute Permissions The file type described above is defined in POSIX to check these types of macro definitions S_ILNK (ST_MODE) judgment whether or not the symbol connection S_ISREG (ST_MODE) is a general file S_ISDIR (ST_MODE) Whether or not a directory s_ischr (ST_MODE) is a character device file S_ISBLK (S3E) whether it is a first-out S_ISSock (ST_MODE) whether it is a Socket if a directory has a Sticky bit (S_ISVTX), indicates that the file in this directory is only Can be removed or renamed by the file owner, this directory owner or root. return value

If the execution is successful, it returns 0, the failure returns -1, the error code exists in Errno

error code

Enoent Parameters File_name The specified file does not exist in the Enotdir path existence but the file that is not true directory ELOOP has too many symbolic connection issues, the upper limit is 16 symbols Connect EFault parameter buf is an invalid pointer, pointing to the memory space that cannot be present. Eaccess Accesses the file when you reject the enamem core memory, the enametoolong parameter file_name path name is too long

example

#include #include mian () {struct stat buf; stat ("/ etc / passwd", & buf); printf ("/ etc / passwd file size =% d / n ", Buf.st_size);

carried out

/ etc / passwd file size = 705

Symlink (create file symbolic connection)

related functions

Link, unlink

Header file

#include

Definition function

Int Symlink (const char * oldpath);

Function description

Symlink () Create a new connection (symbolic connection) to the existing file specified by the parameter OldPath as specified by the name of the parameter newpath. The file specified by the parameter OldPath is not necessarily existing. If the name of the parameter newPath specifies the existing file, it will not be established. return value

Success returns 0, failed to return -1, and the error is existed in Errno.

error code

Eperm Parameters OldPath and NewPath The file system referred to in NEWPATH does not support symbolic connection Erofs to test write permissions files existing in the read-only file system EFault Parameters OldPath or NewPath pointers beyond accessible memory space. ENAMETOOLONG Parameters OldPath or NewPath Too long EnomeM core memory instead EEXIST parameter NewPath refers to the file names already exist. EMLINK Parameter OldPath refers to the maximum number of connections ELOOP parameter Pathname has excessive symbolic connection problem ENOSPC file system remaining space EIO I / O access error

example

#include main () {symlink ("/ etc / passwd", "pass");}

TELLDIR (acquired directory stream)

related functions

Open, OpenDir, Closedir, Rewinddir, Seekdir, Readdir, Scandir

Header file

#include

Definition function

OFF_T TELLDIR (DIR * DIR);

Function description

TELLDIR () Returns the current read location of the parameter DIR directory stream. This return value represents the offset return value at the beginning of the directory file, returns the next read position, and returns -1 when an error occurs.

error code

The eBadf parameter DIR is an invalid directory stream.

example

#include #include #include main () {DIR * DIR; Struct Dirent * Ptr; Int Offset; Dir = Opendir ("/ etc / rc.d "); While ((ptr = readdir (dir))! = Null) {offset = TELLDIR (DIR); Printf (" D_NAME:% s Offset:% D / N ", PTR-> D_Name, Offset;} Closedir (DIR);

carried out

D_name:. OFFSET: 12D_NAME: .. OFFSET: 24D_NAME: INIT.D Offset: 56d_name: rc1.d Offset: 72D_Name: rc2.d Offset: 88d_name: rc3.d Offset 104d_name: rc4.d Offset : 120D_name: rc5.d Offset: 136d_name: rc6.d Offset: 152d_name: rc offset 164d_name: rc.local offset: 180d_name: rc.system offset: 4096

Truncate (change file size)

related functions

Open, FTRUNCATE

Header file

#include

Definition function

INT truncate (const char * path, off_t length);

Function description

TRUNCATE () change the file size specified by the parameter path to the size specified by the parameter length. If the original file size is larger than the parameter length, the more than the part will be deleted.

return value

If the execution is successful, it returns 0, the failure returns -1, and the error is existed in Errno.

error code

The file specified by the EACcess parameter PATH cannot be accessed. Erofs wants to write files exists in the read-only file system EFault parameter PATH pointer exceeds the access memory space EINVAL parameter PATH contains unlamed characters ENAMETOOLONG parameter PATH Too long enotdir parameter PATH Path Patter Path Pointing a directory ETXTBUSY parameter The file referred to in PATH is a shared program, and is being executed in the ELOOP parameter path 'has too many symbolic connection issues EIO I / O access error. Umask (Set the permissions when establishing new files)

related functions

Creat, Open

Header file

#include #include

Definition function

Mode_t umask; Mode_t Mask;

Function description

Umask () will set the system umask value to the value after the Mask & 0777, and then return the previous UMASK value. When using Open () to create a new file, this parameter mode is not the permission of the file, but the authority value of (Mode & ~ UMASK). For example, specifying file permissions when establishing a file, usually umask value defaults to 022, the authenticity of the file is 0666 & ~ 022 = 0644, that is, RW-R - R - Return value will not have The error value is returned. The return value is the UMASK value of the original system.

Unlink (deleted file)

related functions

Link, Rename, Remove

Header file

#include

Definition function

Int unlink (const char * pathname);

Function description

Unlink () will delete the file specified by the parameter pathname. If the file name is the last connection point, but there are other processes to open this file, the file description words on this file are removed after all the file description words are turned off. This connection will be deleted if the parameter PathName is a symbolic connection.

return value

Success returns 0, failed to return -1, the error is existed in Errno

error code

Erofs file exists in read-only file system EFAULT parameter Pathname pointer exceeds the accessible memory space Enametoolong parameter Pathname too long Enoad core memory insufficient ELOOP parameter Pathname has excessive symbolic connection problem EIO I / O Acquisition error

Utime (modify the access time and change time of the file)

related functions

Utimes, Stat

Header file

#include #include

Definition function

INT Utime (const char * filename, struct utimbuf * buf);

Function description

Utime () is used to modify the inode access time to which the parameter filename file belongs. Structure UTIMBUF Defines the following struct utimbuf {time_t actime; time_t modtime;};

return value

If the parameter buf is an empty pointer (NULL), the access time and change time of the file will be set to the current time. If the execution is successful, it returns 0, the failure returns -1, and the error code exists in Errno.

error code

Eaccess is rejected when you have access to files, and the privilege does not exist.

Utimes (modify the access time and change time of the file)

related functions

Utime, Stat

Header file

#include #include

Definition function

INT utimes (char * filename.struct timeval * TVP);

Function description

UTIMES () is used to modify the inode access time and modification time belonging to the parameter filename file. Structure TimeVal defines the following struct timeval {long TV_sec; long TV_usec; ​​/ * subtle * /}; return value

The parameter TVP points to the two TimeVal structural spaces, and the utimebuf structure used by utime (), TVP [0] .tc_sec is utimbuf.actime, TVP] 1] .tv_sec is uTimbuf.Modtime. Returns 0 after success. Failure returns -1, the error code exists in Errno.

error code

Eaccess is rejected when you have access to the file, the permissions are insufficient, the files specified by EACs do not exist.

Access (determined if there is access to access file)

related functions

Stat, Open, Chmod, Chown, SetUID, Setgid

Header file

#include

Definition function

INT Access (const char * pathname, int mode);

Function description

Access () will check if you can read / write an existing file. Several cases of parameter modes, R_OK, W_OK, X_OK, and F_OK. R_OK, W_OK and X_OK are used to check if the file has permission to read, write, and execute. F_ok is used to determine if the file exists. Since Access () is only permissible verification, it is ignored that the file form or file content, so if a directory is "writable", it means that you can create new files in this directory, not this directory. It is treated as a file. For example, you will find that DOS files have "executable" permissions, but it will fail with Execve ().

return value

If all the permissions of all desired nuclear returns 0 values, it returns to -1 as long as one permission is disabled.

error code

The EACcess parameter Pathname specified by the file does not meet the permissions of the required test. Erofs wants to test files that write authorities exist within read-only file systems. The EFAULT parameter Pathname pointer exceeds the accessible memory space. The EINVAL parameter mode is incorrect. ENAMETOOLONG parameter Pathname is too long. Enotdir parameter pathname is a directory. The ENOMEM core is not enough ELOOP parameter pathname has excessive symbolic connection issues. EIO I / O Access error.

Additional information

The judgment of using Access () to operate is especially careful, for example, in Access (), the open () empty file may cause system security issues.

example

/ * Judgment whether to read / etc / passwd * / # include int main () {ix ("/ etc / passwd", r_ok) = = 0) Printf ("/ etc / passwd can Be read / n ");

carried out

/ etc / passwd can be ready

Alphasort (sorted by alphabetical order)

related functions

Scandir, QSORT

Header file

#include

Definition function

Int alphasort (const struct Dirent ** b);

Function description

AlphaSort () is transmitted to QSort () as a function of QSORT () for Scandir (), for details, please refer to Scandir () and QSort ().

return value

Refer to QSORT ().

example

/ * All directory structures under the read / directory, and arrange * / main () {struct Dirent ** Namelist; int i, total; total = scandir ("/", & namelist, 0, alphasort); if (Total <0) PERROR ("scandir"); else {for (i = 0; i D_NAME); Printf ("Total =% D / N ", TOTAL);}}

... gnome.gnome_privateerrorlogweblogbinbootdevdoscdosdetchomeliblost FoundMiscmNToptProcrootsbintmpusrvartotal = 24

CHDIR (Change the current work (directory)

related functions

Getcwd, chroot

Header file

#include

Definition function

INT ChDIR (Const Char * PATH);

Function description

CHDIR () is used to change the current working directory to the directory referred to in parameter PATH.

return value

Returns 0, fail back -1, errno is the error code.

example

#include main () {chdir ("/ tmp"); Printf ("Current Working Directory: S / N", getCwd (null, null);}

carried out

Current Working Directory: / TMP

CHMOD (change file permission)

related functions

FCHMOD, Stat, Open, Chown

Header file

#include #include

Definition function

Int chmod (const char * path, mode_t mode);

Function description

CHMOD () will change the permissions of the parameter PATH specified file according to the parameter MODE permission.

parameter

The Mode has the following several combined S_ISUID 04000 files (SET Group-id ON Execution) bit S_ISGID 02000 file S_ISVTX 01000 file S_Ir (S_IREAD) 00400 file owner readable Permissions S_IWUSR (S_IWRITE) 00200 file owner can write permission s_ixusr (s_iexec) 00100 file owner's executable permission S_IRGRP 00040 user group readable permissions S_IWGRP 00020 user group can write access rights S_IXGRP 00010 user group Execution Permissions S_IROTH 00004 Other Users Read Permissions S_IWOTH 00002 Other Users Other Users S_IXOTH 00001 Other Users Other Permissions Only the owner or valid user identification code of the file is 0 to modify the file permission. Based on system security, if you want to write data to an executable file, the execution file has S_ISUID or S_ISGID permissions, the two bits will be cleared. If a directory has S_ISUID bit permissions, it indicates that only the owner or root of the file in this directory can delete the file.

return value

Permission changes have successfully returned 0, failed to return -1, and the error is existed in Errno.

error code

Eperm process's valid user identification code is different from file owners who want to modify their permissions, and nor root privileges. The file specified by the EACcess parameter PATH cannot be accessed. Erofs wants to write to the permissions to exist within the read-only file system. The Efault parameter PATH pointer exceeds the accessible memory space. ENVAL parameter MODE incorrect Enametoolong Parameter Path Too long enphotd specified files There is no enotdir parameter Path path is not a directory ENOMEM core memory instead of ELOOP parameter PATH has too many symbolic connection issues. EIO I / O Acquisition Error Example

/ * Set / etc / passwd file permissions to S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH> #include #include main () {chmod ("/ etc / passwd" , S_irusr | s_iwusr | s_irgrp | s_iroth;}

Chown (change the owner of the file)

related functions

FChown, LChown, Chmod

Header file

#include #include

Definition function

INT Chown (const char * path, uid_t owner, gid_t group);

Function description

Chown () will change the owner of the parameter PATH to the user representative of the parameter OWNER, and the group of the file is more parameter group group. If the parameter OWNER or group is -1, the corresponding owner or group will not change. All root and file owners can change the file group, but the owner must be a member of the parameter group group. When the root changes the file owner or group with chown (), the file is cleared if the file has S_ISUID or S_ISGID permissions, and if there is S_IxGID permissions but not the S_IXGRP bit, the file will be forced to lock, file mode Will retain.

return value

Success returns 0, failed to return -1, and the error is existed in Errno.

error code

Refer to chmod ().

example

/ * Set the owner and group of / etc / passwd all set to root * / # include #include main () {chown ("/ etc / passwd", 0,0 }

Chroot (Change Root Catalog)

related functions

chdir

Header file

#include

Definition function

INT Chroot (const char * path);

Function description

Chroot () is used to change the root directory as the directory specified by the parameter PATH. Only super users allow changing the root directory, the child process will inherit the new root directory.

return value

When the call is successful, it returns 0, and the failed is returned to -1, and the error code exists in Errno.

error code

Eperm privilege is not possible to change the root directory. The Efault parameter PATH pointer exceeds the accessible memory space. ENAMETOOLONG parameter PATH is too long. The directory in the EnotDir path exists but is not a real directory. The EACcess is rejected when the cordial memory is insufficient. The ELOOP parameter PATH has too many symbolic connection issues. EIO I / O Access error.

example

/ * Change the root directory to / TMP and switch the working directory to / tmp * / # include main () {chroot ("/ tmp"); chDIR ("/");}

CloseDir (turn off the directory)

related functions

OpenDir

Header file

#include #include

Definition function

INT CloseDir (Dir * Dir);

Function description

CloseDir () Close the directory stream referred to in the parameter DIR.

return value

When the shutdown is successful, it returns 0, the failure returns -1, the error is existed in Errno.

error code

Ebadf parameter DIR is invalid to directory flow

example

Refer to readir ().

FCHDIR (change the current work directory)

related functions

Getcwd, chroot

Header file

#include

Definition function

INT FCHDIR (INT FD);

Function description

FCHDIR () is used to change the current work directory into file descriptors referred to as parameter fd.

Return value

Return to 0, the failure returns -1, errno is the error code.

Additional information

example

#include #include #include #include main () {int fd; fd = open ("/ tmp", o_rdonly) FCHDIR (FD); Printf ("Current Working Directory:% S / N", GetCwd (NULL, NULL); Close (FD);}

carried out

Current Working Directory: / TMP

FCHMOD (Permissions to change the file)

related functions

CHMOD, Stat, Open, Chown

Header file

#include #include

Definition function

INT FCHMOD (int Fildes, Mode_t Mode);

Function description

Fchmod () will change the permissions of the files nortified by the parameter Fildes according to the parameter MODE permissions. Parameters Fildes are file descriptors that have been opened. Please refer to chmod ().

return value

Returning 0, returns -1, the error is stored in Errno.

wrong reason

Ebadf Parameters Fildes are invalid file descriptors. Eperm process's valid user identification code is different from file owners who want to modify the permissions, and nor root privileges. Erofs wants to write to the permissions to exist within the read-only file system. EIO I / O Access error.

example

#include #include main () {int fd; fd = open ("/ etc / passwd", o_rdonly); FCHMOD (FD, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); Close (fd);}

FChown (the owner of the file)

related functions

Chown, LChown, Chmod

Header file

#include #include

Definition function

INT FCHOWN (INT FD, UID_T OWNER, GID_T Group);

Function description

FCHOWN () will change the owner of the parameter FD to specify the file as the user representing the parameter Owner, and the group of the file is more than the group group. If the parameter Owner or Group is -1, the designer or group has changed. The parameter fd is the open file descriptor. When the root changes the file owner or group with FCHOWN (), this file will be cleared if you have S_ISUID or S_ISGID permissions.

return value

Success returns 0, and the failure returns -1, and the error is existed in Errno.

error code

Ebadf parameter fd file description word is invalid or the file is closed. Eperm process's valid user identification code is different from the file owner who wants to modify the permissions, and it does not have root privileges, or parameter Owner, Group is incorrect. Erofs wants to write files exist within read-only file systems. EIO I / O Acquiry Evolution Examples

#include #include #include main () {int fd; fd = open ("/ etc / passwd", o_rdonly); chown (fd, 0, 0); Close (FD);

FSTAT (file status by file description words)

related functions

Stat, Lserve, Chmod, Chown, Readlink, Utime

Header file

#include #include

Definition function

INT FSTAT (INT FILDES, STRUCT STAT * BUF);

Function description

FSTAT () is used to copy the file status referred to by the parameter Fildes into the structure referred to in the parameter BUF (Struct Stat). FSTAT () is identical to the stat () effect, and the different parameters are the file descriptors that have been opened. For details, please refer to Stat ().

return value

If the execution is successful, it returns 0, the failure returns -1, and the error code exists in Errno.

example

#include #include #include main () {struct statue; int fd; fd = open ("/ etc / passwd", o_rdonly); fstat FD, & BUF); Printf ("/ etc / passwd file size % d / n", buf.st_size;}

carried out

/ etc / passwd file size = 705

Ftruncate (change file size)

related functions

Open, Truncate

Header file

#include

Definition function

INT FTRUNCATE (INT FD, OFF_T Length);

Function description

Ftruncate () change the file size specified by the parameter FD to the size specified by the parameter length. The parameter fd is the open file descriptor, and must be filed in a write mode. If the original file size is larger than the parameter length, the more than the part will be deleted.

return value

If the execution is successful, it returns 0, the failure returns -1, and the error is existed in Errno.

error code

Ebadf parameter fd file description word is invalid or the file is closed. The EINVAL parameter fd is a socket is not a file, or the file is not open in writing mode.

GetCwd (get the current work directory)

related functions

GET_CURRENT_DIR_NAME, GETWD, CHDIR

Header file

#include

Definition function

Char * getcwd (char * buf, size_t size);

Function description

GetCWD () copies the current working directory absolute path to the memory space referred to by the parameter BUF, and the parameter size is the space size of the BUF. When calling this function, the memory space referred to in BUF is large enough. If the string length of the working directory absolute path exceeds the parameter size size, the value null, the value of Errno is ERANGE. If the parameter buf is null, getCWD () automatically configures memory according to the size of the parameter size (using malloc ()), if the parameter size is also 0, the getCWD () will determine the degree of the string of the work directory absolute path. The memory size, the process can use free () to release this space after using this string. return value

After success, copy the result to the memory space referred to in the parameter BUF, or return the auto-configured string pointer. Failure returns NULL, the error code is existed in Errno.

example

#include main () {char Buf [80]; getCwd (buf, sizeof (buf)); Printf ("Current Working Directory:% S / N", BUF);

carried out

Current Working Directory: / TMP

LINK (establish a file connection)

related functions

Symlink, unlink

Header file

#include

Definition function

INT LINK (Const Char * OldPath, Const Char * NewPath);

Function description

LINK () creates a new connection (hard connection) to the existing file specified by the parameter OldPath as specified by the name of the parameter newpath. If the name specified by the parameter newpath is not established.

return value

Success returns 0, failed to return -1, and the error is existed in Errno.

Additional information

The hard connection established by LINK () cannot span different file systems. If you need, please use SymLink ().

error code

The ExDev parameter OldPath and NewPath are not built in the same file system. Eperm Parameters OldPath and NewPath The file system referred to in NewPath does not support hard connection EROFS files exists in the read-only file system EFault parameter OldPath or NewPath pointer exceeds the accessible memory space. Enametollong Parameters OldPath or NewPath Too long EnomeM core memory instead EEXIST parameter NewPath refers to the file names already exist. The file referred to in the EMLINK parameter OldPath has reached the maximum number of connections. Eloop Parameters Pathname has excessive symbolic connection issues the remaining space of the ENOSPC file system. EIO I / O Access error.

example

/ * Establish / etc / passwd hard connection to pass * / # include main () {link ("/ etc / passwd", "pass");}

LSTAT (File status by file description word)

related functions

Stat, Fstat, Chmod, Chown, Readlink, Utime

Header file

#include #include

Definition function

INT LSTAT (Const Char * file_name.struct stat * buf);

Function description

LSTAT () is identical to the stat () effect, all of which acquire the file status referred to in parameter file_name, and the difference is that when the file is a symbolic connection, LSTAT () will return the status of the Link itself. For details, please refer to Stat ().

return value

If the execution is successful, it returns 0, the failure returns -1, and the error code exists in Errno.

example

Refer to STAT ().

OpenDir (Open Directory)

Related functions open, readdir, closedir, rewinddir, seekdir, telldir, scandir

Header file

#include #include

Definition function

Dir * OpenDir (const char * name);

Function description

OpenDIR () is used to open the directory specified by the parameter name and return the DIR * Form of the directory stream, and Open () is similar to the next reading and search of the directory to use this return value.

return value

Success returns a directory stream of the DIR * type, returns NULL.

error code

EACCESS privileges The EMFILE has reached the number of files that can be opened at the same time. Enfile has reached the upper limit of the number of files that can be opened at the same time. Enotdir Parameters Name NAME NAME The specified directory does not exist, or the parameter Name is an empty string. EnomeM core is insufficient.

Readdir (read directory)

related functions

Open, OpenDir, Closedir, Rewinddir, Seekdir, Telldir, Scandir

Header file

#include #include

Definition function

Struct Dirent * Readdir (Dir * Dir);

Function description

ReadDir () Returns the next directory entry point of the parameter DIR directory stream. Structure dirent defined as follows struct dirent {ino_t d_ino; ff_t d_off; signed short int d_reclen; unsigned char d_type; har d_name [256;}; d_ino directory entry point inoded_off directory file at the beginning of this directory into the longitudinal displacement d_reclen _name point, The file type D_Name file name referred to without NULL character D_Type D_Name

return value

Success returns to the next directory entry point. Returns NULL if there is an error or read to the directory file.

Additional information

The eBadf parameter DIR is an invalid directory stream.

example

#include #include #include main () {DIR * DIR; Struct Dirent * Ptr; INT i; DIR = Opendir ("/ etc / rc.d "); While (ptr = readdir (dir))! = Null) {Printf (" D_NAME:% S / N ", PTR-> D_NAME);} Closedir (DIR);}

carried out

d_name: .d_name: .. d_name: init.dd_name: rc0.dd_name: rc1.dd_name: rc2.dd_name: rc3.dd_name: rc4.dd_name: rc5.dd_name: rc6.dd_name: rcd_name: rc.locald_name: rc.sysinit

Readlink (acquired files referred to)

related functions

Stat, Lstat, Symlink

Header file

#include

Definition function

Int Readlink (const char * path, char * buf, size_t bufsiz);

Function description

ReadLink () will save the parameter PATH symbol connection content to the memory space referred to by the parameter BUF, and the return content is not ending with a NULL string, but returns the character number of the string. If the parameter bufsiz is less than the content length of the symbol connection, the excessive content will be truncated. return value

Perform success, the file path string referred to by the symbol connection, the failure returns -1, the error code exists in Errno.

error code

Eaccess is rejected when the file is taken, the permissions are not enough EIINVAL parameter bufsiz is negative EIO I / O access error. Eloop wants to open with excessive symbolic connection issues. Enametoolong Parameter PATH Path Name Tap too long Enoent Parameters PATH The specified file does not exist in the EnOMem core memory instead of the eNOTDIR parameter Path path in the directory in the path, but is not a real directory.

REMOVE (delete file)

related functions

Link, rename, unlink

Header file

#include

Definition function

Int Remove (const char * pathname);

Function description

REMOVE () will delete the file specified by the parameter pathname. If the parameter PathName is a file, the unlink () process is called. If the parameter PathName is a directory, then RMDIR () is called. Please refer to UNLINK () and RMDir ().

return value

Success returns 0, and the failure returns -1, and the error is existed in Errno.

error code

Erofs wants to write files exists in the read-only file system EFault parameter Pathname pointer exceeds the accessible memory space Enametoolong parameter Pathname too long Enome core memory instead ELOOP parameter Pathname has too multi-symbolic connection problem EIO I / O Acquisition error.

Rename (change the file name or location)

related functions

Link, Unlink, Symlink

Header file

#include

Definition function

Int rename (const char * oldpath, const char * newpath);

Function description

Rename () will change the file name specified by the parameter OldPath to the file name indicated by the parameter newPath. If the file specified by NewPath already exists, it will be deleted.

return value

If the execution is successful, it returns 0, the failure returns -1, and the error is existed in Errno.

example

/ * Design a rename instruction under a DOS Rename old file name new file name * / # include void main (int argc, char ** argv) {if (argc <3) {printf ("Usage:% S OLD_NAME New_NAME / N ", Argv [0]); Return;} Printf ("% s =>% s ", argc [1], argv [2]); if (rename (Argv [1], Argv [2 ] <0) Printf ("error! / N"); Elseprintf ("ok! / N");}

ReWinddir (Reset Reading Directory is starting)

related functions

Open, OpenDir, Closedir, Telldir, Seekdir, Readdir, Scandir

Header file

#include #include

Definition function

Void Rewinddir (Dir * Dir);

Function description

ReWindDir () is used to set the current read position of the parameter DIR directory stream as the original opening position.

return value

error code

Ebadf Dir is invalid to directory flow

example

#include #include #include main () {DIR * DIR; Struct Dirent * Ptr; DIR = OpenDir ("/ etc / rc.d"); While (PTR = ReadDir (Dir))! = null) {Printf ("D_NAME:% S / N", PTR-> D_NAME);} REWINDDIR (DIR); Printf ("Readdir Again! / N"); while ((ptr = readdir (dir))! = null) {Printf ("D_NAME:% S / N", PTR-> D_NAME);} CloseDir (DIR);}

d_name: .d_name: .. d_name: init.dd_name: rc0.dd_name: rc1.dd_name: rc2.dd_name: rc3.dd_name: rc4.dd_name: rc5.dd_name: rc6.dd_name: rcd_name: rc.locald_name: rc.sysinitreaddir again d_name:! .d_name: .. d_name: init.dd_name: rc0.dd_name: rc1.dd_name: rc2.dd_name: rc3.dd_name: rc4.dd_name: rc5.dd_name: rc6.dd_name: rcd_name: rc.locald_name: rc .sinit

Seekdir (Set the location of the reading directory)

related functions

Open, OpenDir, Closedir, Rewinddir, Telldir, Readdir, Scandir

Header file

#include

Definition function

Void seekdir (Dir * Dir, OFF_T OFFSET);

Function description

Seekdir () is used to set the current read position of the parameter DIR directory stream, and read it from this new location when calling readir (). Parameter OFFSET represents the offset at the beginning of the directory file.

return value

error code

Ebadf parameter DIR is invalid to directory flow

example

#include #include #include main () {DIR * DIR; STRUCT DIRENT * PTR; int offset, offset_5, i = 0; Dir = OpenDir (" /etc/rc.d" ";while((((((((ptr = readdir (dir))! = null) {offset = telldir (Dir); if ( i == 5) Offset_5 = Offset; Printf ("d_name:% S Offset:% D / N ", PTR-> D_NAME, OFFSET); SEEKDIR (Dir Offset_5); Printf (" ReadDir Again! / N "); While (Ptr = ReadDir (Dir))! = null) { OFFSET = TELLDIR (DIR); Printf ("D_Name:% S Offset:% D / N", PTR-> D_Name.Offset);} Closedir (DIR);}

carried out

D_name:. OFFSET: 12D_NAME: .. OFFSET: 24D_NAME: INIT.D Offset: 56d_name: rc1.d Offset: 72D_Name: rc2.d Offset: 88d_name: rc3.d Offset 104d_name: rc4.d Offset : 120d_name: rc5.d offset: 136d_name: rc6.d offset: 152d_name: rc offset 164d_name: rc.local offset: 180d_name: rc.sysinit offset: 4096readdir again d_name:! rc2.d offset: 88d_name: rc3.d offset 104d_name : rc4.d Offset: 120d_name: rc5.d Offset: 136d_name: rc6.d Offset: 152D_Name: RC Offset 164D_Name: Rc.local Offset: 180D_Name: rc.sinit offset: 4096stat (get file status)

related functions

FSTAT, LSTAT, Chmod, Chown, Readlink, Utime

Header file

#include #include

Definition function

Int Stat (const char * file_name, struct stat * buf);

Function description

STAT () is used to copy the file status referred to by parameter file_name to the structure referred to in the parameter buf. Here is the description of the parameters in the struct status structure struct stat {dev_t st_dev; / * device * / ino_t ST_INO; / * Inode * / Mode_t ST_MODE; / * Protection * / NLINK_T ST_NLINK; / * NUMBER OF HARD LINKS * / UID_T ST_UID; / * user ID of owner * / gid_t st_gid; / * group ID of owner * / dev_t st_rdev; / * device type * / off_t st_size; / * total size, in bytes * / unsigned long st_blksize; / * blocksize for filesystem I / O * / unsigned long st_blocks; / * number of blocks allocated * / time_t st_atime; / * time of lastaccess * / time_t st_mtime; / * time of last modification * / time_t st_ctime; / * time of last change * /}; The I-NODEST_MODE file of the device number ST_INO file of the ST_DEV file is connected to the number of the hard connection of the file, and the file value of the original file is 1. The ST_UID file owner's user identification code ST_GID file owner's Uncam ST_RDEV If this file is a device file, the device number ST_SIZE file size is used to calculate the I / O buffer size of the ST_BLKSIZE file system. ST_BLCOKS occupies the number of file blocks, each block size of 512 bytes. The ST_AATIME file is only available for the time being accessed or executed. It is generally only changed when using MKNOD, UTIME, READ, WRITE and TRUCTATE.

The ST_MTIME file last changes time, generally only change the time that ST_CTIME I-NODE is changed in the last time with mknod, utime and write, this parameter is updated in the file owner, group, and permissions. st_mode description defines the following several cases S_IFMT 0170000 file type bit mask S_IFSOCK 0140000 scoketS_IFLNK 0120000 symbolic link file S_IFBLK 0060000 S_IFREG 0100000 general block directory means S_IFDIR 0040000 S_IFCHR 0020000 character means S_IFIFO 0010000 S_ISUID 04000 FIFO file ( SET User-id ON Execution) Bit S_ISGID 02000 file S_ISVTX 01000 file Sticky bit s_irusr (s_iread) 00400 file owner readable permission S_IWUSR (S_IWRITE) 00200 file owner Write permission s_ixusr (s_iexec) 00100 File All Act Implementation S_IRGRP 00040 User Pack Read Permissions S_IWGRP 00020 User Pack Writer S_IXGRP 00010 User Pack Excerpt S_Iroth 00004 Other User Ready Permissions S_IWOTH 00002 Other Users Write Permissions S_IXOTH 00001 Other Users Execute Permissions The file type described above is defined in POSIX to check these types of macro definitions S_ILNK (ST_MODE) judgment whether or not the symbol connection S_ISREG (ST_MODE) is a general file S_ISDIR (ST_MODE) Whether or not a directory s_ischr (ST_MODE) is a character device file S_ISBLK (S3E) whether it is a first-out S_ISSock (ST_MODE) whether it is a Socket if a directory has a Sticky bit (S_ISVTX), indicates that the file in this directory is only Can be removed or renamed by the file owner, this directory owner or root. return value

If the execution is successful, it returns 0, the failure returns -1, the error code exists in Errno

error code

Enoent Parameters File_name The specified file does not exist in the Enotdir path existence but the file that is not true directory ELOOP has too many symbolic connection issues, the upper limit is 16 symbols Connect EFault parameter buf is an invalid pointer, pointing to the memory space that cannot be present. Eaccess Accesses the file when you reject the enamem core memory, the enametoolong parameter file_name path name is too long

example

#include #include mian () {struct stat buf; stat ("/ etc / passwd", & buf); printf ("/ etc / passwd file size =% d / n ", Buf.st_size);

carried out

/ etc / passwd file size = 705

Symlink (create file symbolic connection)

related functions

Link, unlink

Header file

#include

Definition function

Int Symlink (const char * oldpath);

Function description

Symlink () Create a new connection (symbolic connection) to the existing file specified by the parameter OldPath as specified by the name of the parameter newpath. The file specified by the parameter OldPath is not necessarily existing. If the name of the parameter newPath specifies the existing file, it will not be established. return value

Success returns 0, failed to return -1, and the error is existed in Errno.

error code

Eperm Parameters OldPath and NewPath The file system referred to in NEWPATH does not support symbolic connection Erofs to test write permissions files existing in the read-only file system EFault Parameters OldPath or NewPath pointers beyond accessible memory space. ENAMETOOLONG Parameters OldPath or NewPath Too long EnomeM core memory instead EEXIST parameter NewPath refers to the file names already exist. EMLINK Parameter OldPath refers to the maximum number of connections ELOOP parameter Pathname has excessive symbolic connection problem ENOSPC file system remaining space EIO I / O access error

example

#include main () {symlink ("/ etc / passwd", "pass");}

TELLDIR (acquired directory stream)

related functions

Open, OpenDir, Closedir, Rewinddir, Seekdir, Readdir, Scandir

Header file

#include

Definition function

OFF_T TELLDIR (DIR * DIR);

Function description

TELLDIR () Returns the current read location of the parameter DIR directory stream. This return value represents the offset return value at the beginning of the directory file, returns the next read position, and returns -1 when an error occurs.

error code

The eBadf parameter DIR is an invalid directory stream.

example

#include #include #include main () {DIR * DIR; Struct Dirent * Ptr; Int Offset; Dir = Opendir ("/ etc / rc.d "); While ((ptr = readdir (dir))! = Null) {offset = TELLDIR (DIR); Printf (" D_NAME:% s Offset:% D / N ", PTR-> D_Name, Offset;} Closedir (DIR);

carried out

D_name:. OFFSET: 12D_NAME: .. OFFSET: 24D_NAME: INIT.D Offset: 56d_name: rc1.d Offset: 72D_Name: rc2.d Offset: 88d_name: rc3.d Offset 104d_name: rc4.d Offset : 120D_name: rc5.d Offset: 136d_name: rc6.d Offset: 152d_name: rc offset 164d_name: rc.local offset: 180d_name: rc.system offset: 4096

Truncate (change file size)

related functions

Open, FTRUNCATE

Header file

#include

Definition function

INT truncate (const char * path, off_t length);

Function description

TRUNCATE () change the file size specified by the parameter path to the size specified by the parameter length. If the original file size is larger than the parameter length, the more than the part will be deleted.

return value

If the execution is successful, it returns 0, the failure returns -1, and the error is existed in Errno.

error code

The file specified by the EACcess parameter PATH cannot be accessed. Erofs wants to write files exists in the read-only file system EFault parameter PATH pointer exceeds the access memory space EINVAL parameter PATH contains unlamed characters ENAMETOOLONG parameter PATH Too long enotdir parameter PATH Path Patter Path Pointing a directory ETXTBUSY parameter The file referred to in PATH is a shared program, and is being executed in the ELOOP parameter path 'has too many symbolic connection issues EIO I / O access error. Umask (Set the permissions when establishing new files)

related functions

Creat, Open

Header file

#include #include

Definition function

Mode_t umask; Mode_t Mask;

Function description

Umask () will set the system umask value to the value after the Mask & 0777, and then return the previous UMASK value. When using Open () to create a new file, this parameter mode is not the permission of the file, but the authority value of (Mode & ~ UMASK). For example, specifying file permissions when establishing a file, usually umask value defaults to 022, the authenticity of the file is 0666 & ~ 022 = 0644, that is, RW-R - R - Return value will not have The error value is returned. The return value is the UMASK value of the original system.

Unlink (deleted file)

related functions

Link, Rename, Remove

Header file

#include

Definition function

Int unlink (const char * pathname);

Function description

Unlink () will delete the file specified by the parameter pathname. If the file name is the last connection point, but there are other processes to open this file, the file description words on this file are removed after all the file description words are turned off. This connection will be deleted if the parameter PathName is a symbolic connection.

return value

Success returns 0, failed to return -1, the error is existed in Errno

error code

Erofs file exists in read-only file system EFAULT parameter Pathname pointer exceeds the accessible memory space Enametoolong parameter Pathname too long Enoad core memory insufficient ELOOP parameter Pathname has excessive symbolic connection problem EIO I / O Acquisition error

Utime (modify the access time and change time of the file)

related functions

Utimes, Stat

Header file

#include #include

Definition function

INT Utime (const char * filename, struct utimbuf * buf);

Function description

Utime () is used to modify the inode access time to which the parameter filename file belongs. Structure UTIMBUF Defines the following struct utimbuf {time_t actime; time_t modtime;};

return value

If the parameter buf is an empty pointer (NULL), the access time and change time of the file will be set to the current time. If the execution is successful, it returns 0, the failure returns -1, and the error code exists in Errno.

error code

Eaccess is rejected when you have access to files, and the privilege does not exist.

Utimes (modify the access time and change time of the file)

related functions

Utime, Stat

Header file

#include #include

Definition function

INT utimes (char * filename.struct timeval * TVP);

Function description

UTIMES () is used to modify the inode access time and modification time belonging to the parameter filename file. Structure TimeVal defines the following struct timeval {long TV_sec; long TV_usec; ​​/ * subtle * /}; return value

The parameter TVP points to the two TimeVal structural spaces, and the utimebuf structure used by utime (), TVP [0] .tc_sec is utimbuf.actime, TVP] 1] .tv_sec is uTimbuf.Modtime. Returns 0 after success. Failure returns -1, the error code exists in Errno.

error code

Eaccess is rejected when you have access to the file, the permissions are insufficient, the files specified by EACs do not exist.

ALARM (setting signal transfer alarm)

related functions

Signal, SLEEP

Header file

#include

Definition function

Unsigned int alarm (unsigned int seconds);

Function description

ALARM () is used to set the signal SIGALRM to transmit to the current process after the number of seconds specified by the parameter seconds. If the parameter seconds is 0, the previous set alarm will be canceled and the remaining time is returned.

return value

Returns the number of remaining seconds of the alarm before returning 0 if the alarm is not set.

example

#include #include void handler () {Printf ("Hello / N");} main () {Int i; signal (sigalrm, handler); Alarm (5); for i = 1; i <7; i ) {Printf ("Sleep% D ... / N", I); SLEEP (1);}}

carried out

Sleep 1 ... Sleep 2 ... Sleep 3 ... Sleep 4 ... Sleep 5 ... Hellosleep 6 ...

Kill (transfer signal to the specified process)

related functions

Raise, Signal

Header file

#include #include

Definition function

INT KILL (PID_T PID, INT SIG);

Function description

Kill () can be used to send the signal specified by the parameter SIG to the process specified by the parameter PID. Several parameters PID: PID> 0 transmits the signal to the process identification code for the PID. PID = 0 Transmits all processes of signal transmission and current procedures PID = -1 to transmit signal broadcast to all process PID <0 to transmit signal to process group identification code for PID absolute values ​​all process parameters SIG Representing the signal number to refer to Appendix D

return value

Returns 0 if there is an error, returns -1 if there is an error.

error code

EINVAL parameter SIG illegal ESRCH Parameter PID The process or process group specified in the PID does not exist that the ePerm permissions are not possible to transfer signals to the specified process.

example

#include #include #include #include main () {pid_t pid; int status; if (! (pid = for) ))) {Printf ("Hi I am CHild Process! / N"); Sleep (10); Return;} else {printf ("Send Signal To Child Process (% D) / N", PID); SLEEP (1 Kill (PID, SIGABRT); WAIT (& Status); if (WiFSignaled (Status)) Printf ("Chile Process Receive Signal D / N", WTERMSIG (STATUS));}}

Sen Signal To Child Process (3170) Hi I am Child Process! Child Process Receive Signal 6

Pause (let the process pause until the signal appears)

related functions

Kill, Signal, Sleep

Header file

#include

Definition function

INT PAUSE (VOID);

Function description

Pause () will save the current process (enter the sleep state) until the signal (Signal) is interrupted.

return value

Returns only -1.

error code

EINTR has a signal to interrupt this function.

SIGACTION (query or setting signal processing mode)

related functions

Signal, SigProcmask, Sigpending, Sigsuspend

Header file

#include

Definition function

Int SigAction (int Signum, Const Struct SigAction * ACT, STRUCT SIGACTION * OLDACT);

Function description

SigAction () will set the processing function of the signal according to the signal number specified by the parameter signum. Parameters Signum can specify all signals other than Sigkill and Sigstop. If the parameter structure is defined as the following Struct SigAction {void (int); sigset_t sa_mask; int sa_flags; void;} SA_HANDLER This parameter is the same as the parameter handler of Signal (), represents new signals Processing functions, please refer to Signal (). SA_MASK is used to set the signal specified by sa_mask when processing the signal. SA_RESTORER This parameter is not used. SA_FLAGS is used to set other related operations for signal processing, the following values ​​available. OR operation (|) combination A_NOCLDSTOP: If the parameter signum is Sigchld, then when the child process is paused, does not inform the parent process SA_ONESHOT / SA_RESETHAND: When the new signal processing function is called, the signal processing is changed to the system preset. the way. SA_RESTART: The system calls that are interrupted will restart SA_NOMASK / SA_NODEFER themselves: I will not ignore this signal again before processing this signal. If the parameter Oldact is not a NULL pointer, the original signal processing will be returned by this structure SigAction.

return value

Returns 0 if there is an error, returns -1 if there is an error.

error code

EINVAL parameter signum is not legal, or attempts to intercept the sigkill / sigstopsigkill signal EFAULT parameter ACT, the Oldact pointer address cannot be accessed. EINTR This call is interrupted

example

#include #include void show_handler (struct sigaction * act) {switch (act-> sa_flags) {copy sig_dfl: Printf ("default action / n"); Break; Case Sig_ign: Printf ("Ignore the Signal / N"); Break; Default: Printf ("0x% x / n", act-> sa_handler);}} main () {INT i; struct sigAnt, oldact; act.sa_handler = show_handler Act.sa_flags = sa_oneshot | sa_nomask; sigction (Sigusr1, & Act, & OLDAC); for (i = 5; i <15; i ) {printf ("SA_HANDLER OF SIGNAL% 2D =". I); Sigction (i, null & Oldact);}}

sa_handler of signal 5 = Default actionsa_handler of signal 6 = Default actionsa_handler of signal 7 = Default actionsa_handler of signal 8 = Default actionsa_handler of signal 9 = Default actionsa_handler of signal 10 = 0x8048400sa_handler of signal 11 = Default actionsa_handler of signal 12 = Default actionsa_handler of signal 13 = Default ActionSA_Handler of Signal 14 = DEFAULT ACTION

SigaddSet (add a signal to the signal set)

related functions

SiGemptyset, SigfillSet, Sigdelset, Sigismember

Header file

#include

Definition function

INT SigaddSet (SIGSET_T * SET, INT SIGNUM);

Function description

SigAddSet () is used to join the signal represented by the parameter Signum to the parameter set signal set.

return value

Returns 0 if there is an error, returns -1 if there is an error.

error code

EFAULT parameter set pointer address Unable to access EINVAL parameter Signum non-legitimate signal number

Sigdelset (delete a signal from the signal set)

related functions

SiGemptySet, Sigfillset, SigaddSet, Sigismember

Header file

#include

Definition function

INT Sigdelset (SIGSET_T * SET, INT SIGNUM);

Function description

Sigdelset () is used to delete the signal represented by the parameter Signum from the parameter set signal set.

return value

Returns 0 if there is an error, returns -1 if there is an error.

error code

EFAULT parameter set pointer address Unable to access EINVAL parameter Signum non-legitimate signal number

SiGemptySet (initialization signal set)

related functions

Sigaddset, SigfillSet, Sigdelset, Sigismember

Header file

#include

Definition function

INT SiGemptySet (SIGSET_T * SET);

Function description

SiGemptySet () is used to set the parameter set signal set and empty.

return value

Returns 0 if there is an error, returns -1 if there is an error.

error code

EFAULT parameter set pointer address cannot be accessed

SIGFILLSET (add all signals to the signal set)

related functions

SiGempty, SigaddSet, Sigdelset, Sigismember

Header file

#include

Definition function

INT SigfillSet (SIGSET_T * SET);

Function description

SigfillSet () is used to set the parameter set signal set, and then all the signals are added to this signal set.

return value

Returns 0 if there is an error, returns -1 if there is an error.

Additional information

EFAULT parameter set pointer address cannot be accessed

SIGISMEMBER (testing some signal has been added to the signal set)

related functions

SiGemptySet, SigfillSet, SigaddSet, Sigdelset

Header file

#include

Definition function

INT Sigismember (const squares); intidum);

Function description

SIGISMEMBER () is used to test whether the signal represented by the parameter Signum has been added to the parameter set signal set. If the signal already has this signal in the signal set, returns 0.

return value

The signal set has been returned to 1, and it is not returned to 0. Returns -1 if there is an error.

error code

EFAULT parameter set pointer address Unable to access EINVAL parameter Signum non-legitimate signal number

Signal (setting signal processing mode)

related functions

SigAction, Kill, Raise

Header file

#include

Definition function

Void (* Signal (Int Signal) (INT)) (INT);

Function description

Signal () will set the processing function of the signal according to the signal numbers specified by the parameter signum. When the specified signal arrives, you will be jumped to the function executed by the parameter handler. If the parameter handler is not a function pointer, it must be one of the following two constants: SIG_IGN ignores the signal specified by the parameter Signum. SIG_DFL resets the signal specified by the parameter Signum into the core preset signal processing mode. For the number and description of the signal, please refer to Appendix D

return value

Returns the previous signal processing function pointer, returns SIG_ERR (-1) if there is an error.

Additional information

After the signal is jumped to the custom Handler handler, the system will automatically change this processing function back to the original system preset processing method. If you want to change this, please use sigAction ().

example

Refer to ALARM () or RAISE ().

SIGPENDING (Signal Signal)

related functions

Signal, SigAction, SigProcmask, Sigsuspend

Header file

#include

Definition function

INT SIGPENDING (SIGSET_T * SET);

Function description

SIGPENDING () will return the hinged signal to the parameter set pointer.

Return value

Row success returns 0, returns -1 if there is an error.

error code

Efault parameter set pointer address cannot access Eintr This call is interrupted.

SigProcmask (query or setting signal mask)

related functions

Signal, SigAction, Sigpending, Sigsuspend

Header file

#include

Definition function

Int SigProcmask (int how, const sigset_t * set, sigset_t * Oldset);

Function description

SigProcmask () can be used to change the current signal mask, which operates as the parameter how to determine the SIG_BLOCK new signal mask by the current signal mask and parameter set as a set SIG_UNBLOCK to make the current signal mask Deleting the signal mask SIG_SETMASK specified by the parameter set SIG_SETMASK sets the current signal mask to the signal mask specified by the parameter set. If the parameter Oldset is not a NULL pointer, the current signal mask will be returned by this pointer.

return value

Returns 0 if there is an error, returns -1 if there is an error.

error code

Efault parameter set, the Oldset pointer address cannot be accessed. EINTR This call is interrupted

SLEEP (let the process pauses for a period of time)

related functions

Signal, Alarm

Header file

#include

Definition function

Unsigned int SLEP (unsigned int seconds);

Function description

Sleep () will save the current process until the time specified by the parameter seconds or is interrupted by the signal.

return value

If the process is paused to the parameter seconds, it returns 0, and if there is a signal interruption, the number of remaining seconds is returned.

FERROR (check if the file flow has an error)

related functions

Clearerr, Perror

Header file

#include

Definition function

INT FERROR (File * stream);

Function description

FERROR () is used to check if the file stream specified by the parameter stream has an error condition, and if there is an error, it returns a non-0 value.

return value

Returns a non-0 value if the file stream occurs.

PERROR (printed error reason information string)

related functions

STRERROR

Header file

#include

Definition function

Void Perror (const char * s);

Function description

PERROR () is used to output the cause of the previous function to the standard error (stderr). The string fingered by the parameter S will print first, and then add an error reason string. This error is determined in accordance with the value of the global variable errno.

return value

example

#include main () {file * fp; fp = fopen ("/ tmp / noexist", "r "); if (fp = = null) PERROR ("fopen");}

carried out

$ ./Perrorfopen: No Such File or DireTory

STRERROR (returning the description string of error reason)

related functions

PERROR

Header file

#include

Definition function

CHAR * STRERROR (int errnum);

Function description

STRERROR () is used to query the description string of its error cause according to the error code of parameter errnum, and then return the string pointer.

return value

Returns a string pointer to describe the cause of the error.

example

/ * Display error Code 0 to 9 Error Cause Description * / # include main () {INT i; for (i = 0; i <10; i ) printf ("% D:% S / N ", I, strerror (i));

carried out

0: Success1: Operation not permitted2: No such file or directory3: No such process4: Interrupted system call5: Input / output error6: Device not configured7: Argument list too long8: Exec format error9: Bad file descriptormkfifo (establishment named pipes)

related functions

PIPE, POPEN, OPEN, UMASK

Header file

#include #include

Definition function

INT MKFIFO (const char * pathname, mode_t mode);

Function description

MKFIFO () will establish a special FIFO file according to the parameter Pathname, which must not exist, and the parameter Mode is the permissions of the file (MODE% ~ umask), so the umask value will also affect the FIFO file. MkfiFo () established FIFO files can be accessed by reading and writing a general file. When using open () to open the FIFO file, the O_NonBlock flag will affect 1. When using the O_NONBLOCK flag, open the FIFO file to read the action, but if there is no other process to open the FIFO file to read Then, the write operation returns Enxio error code. 2. When using the O_NONBLOCK flag, open the FIFO to read the action will wait until other processes open the FIFO file to write to return. Similarly, the operation to open the FIFO file to write will wait until other processes open the FIFO file to read it normally.

return value

If success, return 0, otherwise returns -1, the error is existed in Errno.

error code

EACCESS Parameters Pathname The specified directory path Unhappy Permissions Eexist Parameter Pathname The specified file already exists. The path name of the enametoolong parameter Pathname is too long. The Enoent Parameter Pathname includes the directory of the enospc file system in the enocdir parameter in the ENOTDIR parameter Pathname path, but is not a real directory. Erofs parameter pathname The specified file exists within the read-only file system.

example

#include #include #include main () {char buffer [80]; int fd; unlink (FIFO); MKFIFO (FIFO, 0666); IF (fork ()> 0) {char s [] = "Hello! / n"; fd = open (fix, o_wronly); Write (FD, S, SIZEOF (S)); Close (fd);} else { FD = Open (FIFO, O_RDONLY); Read (FD, Buffer, 80); Printf ("% s", buffer); Close (fd);}}

carried out

Hello!

PCLOSE (shut down pipe I / O)

related functions

Popen

Header file

#include

Definition function

INT PCLOSE (File * Stream);

Function description

PCLOSE () is used to close the pipes and file pointers established by POPEN. The parameter stream is the file pointer previously returned by POPEN ().

return value

The end state of the return child process. Returns -1 if there is an error, and the error is existed in Errno.

error code

Echild PClose () cannot obtain the end of the child process.

example

Refer to POPEN ().

PIPE (establishing pipeline) related functions

MKFIFO, POPEN, Read, Write, Fork

Header file

#include

Definition function

INT PIPE (int filedes [2]);

Function description

PIPE () will establish a pipe and return the file description word by the parameter filedes array. FileDes [0] is the read end in the pipeline, and FileDes [1] is the write end of the pipe.

return value

If success, return zero, otherwise returns -1, the error is existed in Errno.

error code

The Emfile process has been used to complete the file descriptor. Enfile system has no file description words available. Efault parameter filedes array address is not legal.

example

/ * Parent process borrows the pipe to pass the string "Hello! / N" to the child process and display * / # include main () {int filedes [2]; char buffer [80]; PIPE (Filedes) ; if (fork ()> 0) {/ * parent process * / char s [] = "Hello! / n"; Write (Filedes [1], S, SIZEOF (s));} else {/ * child process * / read (Filedes [0], Buffer, 80); Printf ("% s", buffer);}}

carried out

Hello!

POPEN (establish pipeline I / O)

related functions

Pipe, MKFIFO, PClose, Fork, System, Fopen

Header file

#include

Definition function

File * POPEN (const char * type);

Function description

POPEN () will call the fork () generated sub-process, then call / bin / sh -c from the sub-process to execute the instructions of the parameter Command. The parameter TYPE can be read using the "R" representative read, "W" is written. According to this type value, POPEN () will establish a standard output device or standard input device that connects the child process and then returns a file pointer. Subsequent processes can be used to read the file pointer to read the output device of the child or write to the standard input device of the child process. In addition, all functions that use the file pointer (file *) can be used, except for fclose ().

return value

If success, return the file pointer, otherwise return null, and the error is existed in Errno.

error code

The EINVAL parameter TYPE is not legal.

Precautions

When writing Suid / SGID programs, please try to avoid using popen (), POPEN () will inherit environment variables, and can cause system security issues through environmental variables.

example

#include main () {file * fp; char buffer [80]; fp = POPEN ("CAT / ETC / Passwd", "R"); FGETS (Buffer, Sizeof (Buffer), FP); Printf ("% s", buffer; pClose (fp);

carried out

Root: x: 0 0: root: / root: / bin / bash

Accept (Accept Socket Connection)

related functions

Socket, Bind, Listen, Connect

Header file

#include #include

Definition function

INT Accept (int S, Struct SockAddr * Addr, INT * Addrlen);

Function description

Accept () is used to accept the Socket connection of parameter s. The Socket of the parameter S is necessary to process the BIND (), the listen () function, and accept () will return a new socket processing code when there is a connection, and the subsequent data transfer and reading are processed via the new socket. And the original parameter S Socket can continue to use accept () to accept new connection requirements. When the connection is successful, the structure referred to by the parameter addr will be filled in the address data of the remote host, the parameter addrlen is the structural length of Scokdd. For the definition of structure SOCKADDR, please refer to Bind (). return value

Success returns a new Socket processing code, failed to return -1, and the error is existed in Errno.

error code

EBADF parameter S non - legitimate Socket processing code. The Efault Parameters addR pointer points to the memory space that cannot be accessed. EnotSock parameter S is a file descriptor, non-socket. EopnotSupp Specifies Socket Not Sock_Stream. Eperm firewall rejects this connection. The buffering memory of the Enobufs system is insufficient. EnomeM core is insufficient.

example

Refer to Listen ().

Bind (targeting socket)

related functions

Socket, Accept, Connect, Listen

Header file

#include #include

Definition function

INT Bind (int Sockfd, struct sockaddr * my_addr, int addrlen);

Function description

Bind () is used to set a name for the Socket for the parameter sockfd. This name is directed by the parameter my_addr to a SockAddr structure, defines a universal data structure for different socket domain, which is the domain parameter when calling socket () for different socket Domain;}; sa_family AF_XXXX value. SA_DATA uses up to 14 characters long. This sockaddr structure due to the use of different socket domain and have different structure definitions, for example AF_INET domain, which socketaddr structure is defined so as struct socketaddr_in {unsigned short int sin_family; uint16_t sin_port; struct in_addr sin_addr; unsigned char sin_zero [8];} Struct in_addr {uint32_t s_addr;}; sin_family, the port number SIN_ADDR.S_ADDR SIN_ADDR.S_ADDR SIN_ADDR.S_ADDR for SA_FAMILYSIN_PORT is not used by IP addresses SIN_ZERO.

parameter

Addrlen is the structure length of SockAddr.

return value

Success returns 0, the failure returns -1, and the error is existed in Errno.

error code

EBADF parameter sockfd non-legitimate SOCKET processing code. EACCESS permissions The enotsock parameter sockfd is a file descriptor, non-socket.

example

Reference listen ()

Connect (create a Socket connection)

related functions

Socket, Bind, Listen

Header file

#include #include

Definition function

INT Connect (int sockfd, struct sockaddr * serv_addr, int addrlen);

Function description

Connect () is used to connect the parameter sockfd's socket to the network address specified by the parameter serv_addr. Structure SockAddr Please refer to Bind (). The parameter addrlen is the structure length of SockAddr. return value

Success returns 0, the failure returns -1, and the error is existed in Errno.

error code

Ebadf parameter sockfd non-legitimate SOCKET Processing code EFault parameter serv_addr pointer points to the unacceptable memory space EnotSock parameter sockfd is a file descriptor, non-socket. The socket of the Eisconn parameter sockfd is the connection status of the ECONNREFUSED connection request to be rejected by the Server side. ETIMEDOUT attempts to connect operations than limited time still no response. ENETunReach cannot transmit packets to the specified host. The SA_FAMILY of the Eafnosupport SockAddr structure is incorrect. Ealready Socket has not been completed for unbrocessed and previous connection operations.

example

/ * Use the Socket TCP Client This program will connect TCP Server and transfer the keyboard input string to the Server. For the TCP Server example, please refer to Listen (). * / # include #include #include #include #include #include #include #define port 1234 # Define Server_ip "127.0.0.1" main () {int S; struct sockaddr_in addr; char buffer [256]; if ((s = socket (AF_INET, SOCK_STREAM 0)) <0) {PERROR ("socket"); exit (1);} / * Fill in the SockAddr_in structure * / Bzero (& addr, sizeof (addr)); addr.sin_family = AF_INET; addr.sin_port = Htons Port); addr.sin_addr.s_addr = inet_addr (server_ip); / * Try connecting * / if (Connect (S, & Addr) <0) {PERROR ("Connect"); exit (1); } / * Receive information from the Server end * / RECV (S, Buffer, Sizeof (Buffer), 0); Printf ("% S / N", Buffer; While (1) {Bzero (Buffer, Sizeof) Buffer); / * Get strings from standard input devices * / read (stdin_fileno, buffer, sizeof (buffer)); / * Pass string to Server * / if (Send (S, Buffer, Sizeof (buffer) , 0) <0) {Perror ("send"); exit (1);}}}

carried out

$ ./connectwelcome to server! hi i amclient! / * Keyboard input * // * interrupt program * /

EndProtoent (reading network protocol data)

related functions

GetProtoent, GetProtobyname, GetProtobynumber, SetProtoent

Header file

#include

Definition function

Void endprotoent (void);

Function description

EndProtoent () is used to close files opened by getProtoent ().

return value

example

Reference getprotoent ()

EndServent (reading of network service data) related functions

GetServent, GetServByname, GetServbyport, SetServent

Header file

#include

Definition function

Void endServent (void);

Function description

EndServent () is used to close the files opened by GetServent ().

return value

example

Refer to GetServent ().

Getsockopt (get a socket status)

related functions

Setsockopt

Header file

#include #include

Definition function

INT GetSockopt (int S, int Level, Int Optname, void * optval, socklen_t * optlen);

Function description

GetSockOpt () returns the Socket status specified by the parameter s. Parameters Optname represents what options to make, and parameter OPTVAL points to the memory address to save the result, and the parameter OPTLEN is the size of the space. Parameters Level, Optname Please refer to SetsockOpt ().

return value

Success, return 0, return -1 if there is an error, the error is existed in Errno

error code

Ebadf parameter S is not legal Socket processing code ENOTSOCK parameter S is a file descriptor, non-socketenoprotoopt parameter Optname specified option incorrect EFAULT parameter Optval pointer points to memory space that cannot be accessed

example

#include #include main () {Int S, OptVal, Optlen = SizeOf (int); if ((S = Socket (AF_INET, SOCK_STREAM, 0)) <0) <0 ) PERROR ("socket"); GetSockopt (S, SOL_Socket, SO_TYPE, & OPTVAL, & OPTLEN); Printf ("OptVal =% D / N", OptVal; Close (s);}

carried out

Optval = 1 / * Sock_Stream definition is this value * /

HTONL (transitioning 32-bit host characters in order to network characters)

related functions

Htons, NTOHL, NTOHS

Header file

#include

Definition function

Unsigned long int htonl;

Function description

HTONL () is used to convert the 32-bit hostlong specified by the parameter into a network character order.

return value

Returns the corresponding network character sequence.

example

Refer to GetServByPort () or Connect ().

Htons (transitioning 16 host characters in the order of network characters)

related functions

HTONL, NTOHL, NTOHS

Header file

#include

Definition function

UNSIGNED SHORT INT HTONS (UNSIGNED SHORT INT HOSTSHORT);

Function description

Htons () is used to convert the 16-bit hostshorts specified by the parameter into a network character order.

return value

Returns the corresponding network character sequence.

example

Refer to Connect ().

INET_ADDR (transfer network address to binary)

related functions

inet_aton, inet_ntoa

Header file

#include #include #include definition function

Unsigned long int inet_addr (const char * cp);

Function description

INET_ADDR () is used to convert the network address string referred to in the parameter CP into a binary number used by the network. The network address string is a string consisting of numbers and points, such as "163.13.132.68".

return value

Success returns to the corresponding network binary number, failed to return -1.

inet_aton (transfer network address to network binary)

related functions

INET_ADDR, INET_NTOA

Header file

#include #include #include

Definition function

INT INET_ATON (Const Char * CP, Struct In_Addr * INP);

Function description

inet_aton () is used to convert the network address string referred to in the parameter CP into a binary number used, and then exist in the IN_ADDR structure referred to in the parameter INP. Structure in_addr Defines the following struct in_addr {unsigned long int s_addr;};

return value

Success returns a non-0 value and returns 0.

INET_NTOA (converting network binary numbers into network addresses)

related functions

inet_addr, inet_aton

Header file

#include #include #include

Definition function

Char * inet_ntoa (struct in_addr in);

Function description

INET_NTOA () is used to convert the network binary numbers referred to in the parameter in to the network address, and then returns the pointer to this network address string.

return value

Success returns a string pointer and returns NULL.

Listen (wait connection)

related functions

Socket, Bind, Accept, Connect

Header file

#include

Definition function

INT Listen (int S, int backlog);

Function description

Listen () is used to wait for the Socket connection of the parameter S. Parameter backlog Specifies the maximum connection requirements at the same time. If the number of connections reaches the upper limit, the Client end will receive an ECONNREFUSED error. Listen () did not start receiving the connection, just set the socket as the Listen mode, and truly receiving the client connection is Accept (). Usually listen () will be called after socket (), bind (), then call Accept ().

return value

Success returns 0, failed to return -1, the error is existed in Errno

Additional information

Listen () is only applicable to the socket type of Sock_Stream or Sock_seqpacket. If the socket is AF_INET, the parameter backlog maximum can be set to 128.

error code

Ebadf Parameters SOCKFD Non Legal Socket Processing Code EACCESS Permissions The specified Socket is not supported in the Listen mode.

example

#include #include #include #include #include #define port 1234 # Define MaxSockfd 10main () {int sockfd, newsockfd, is_connected [MAXSOCKFD], fd; struct sockaddr_in addr; int addr_len = sizeof (struct sockaddr_in); fd_set readfds; char buffer [256]; char msg [] = "Welcome to server!"; IF ((SOCKFD = Socket (AF_INET, SOCK_STREAM, 0) <0) {Perror ("socket"); exit (1);} Bzero (& addr, sizeof (addr)); addr.sin_family = af_inet; addr.sin_port = htons (port); addr.sin_addr.s_addr = htonl (INADDR_Any); if (Bind (SockFD, & Addr, SizeOf (AddR)) <0) {Perror ("Connect"); exit (1);} if (listen) (SOCKFD, 3) <0) {Perror ("listen"); exit (1);} for (fd = 0; fd

$ ./listenconnect from 127.0.0.1hi i amclientconnected closed.

NTOHL (convert 32-bit network character sequence into host characters)

related functions

HTONL, HTONS, NTOHS

Header file

#include

Definition function

Unsigned long int NTOHL (unsigned long int netlong);

Function description

NTOHL () is used to convert the 32-bit NETLONG specified by the parameter into a host character sequence.

return value

Returns the corresponding host character sequence.

example

Refer to GetServent ().

NTOHS (convert 16-bit network character sequence into host character sequence)

related functions

HTONL, HTONS, NTOHL

Header file

#include

Definition function

UNSIGNED SHORT INT NTOHS (UNSIGNED SHORT INT NETSHORT);

Function description

NTOHS () is used to convert the 16-bit Netshort specified by the parameter to the host character sequence.

return value

Returns the corresponding host order.

example

Refer to GetServent ().

RECV (received data by Socket)

related functions

Recvfrom, Recvmsg, Send, Sendto, Socket

Header file

#include #include

Definition function

INT RECV (Int S, Void * BUF, INT LEN, UNSIGNED INT FLAGS);

Function description

RECV () is used to receive data from the specified Socket specified, and save the data to the memory space pointed to by the parameter BUF, and the parameter LEN is the maximum length of the received data.

parameter

Flags are generally 0. Other values ​​are defined as follows: MSG_oob receives data sent in OUT-OF-BAND. The data returned by MSG_peek does not delete in the system, if the recall RECV () will return the same data content. MSG_WAITALL forced data to receive the Len size before returning, unless there is an error or signal generation. MSG_NOSignal This operation is not willing to be successfully returned by the SIGPIPE signal, returns the number of characters received, and the failure returns -1, and the error is stored in Errno.

error code

Ebadf Parameters S Non Legal Socket Processing Code EFault Parameters There is a pointer pointing to the unacceptable memory space EnotSock parameter S is a file descriptor, non-socket. EINTR is interrupted by the signal to block the process to block the process, but the Socket of the parameter S is insufficient to block the buffer memory that cannot block the Enobufs system. EnomeM core memory is incorrect with EINVAL pass to the system call.

example

Refer to Listen ().

Recvfrom (received data received by Socket)

related functions

RECV, Recvmsg, Send, Sendto, Socket

Header file

#include #include

Definition function

INT Recvfrom (int LEN, Unsigned Int Flags, Struct SockAddr * from, int * fromlen);

Function description

Recv () is used to receive data from the specified Socket, and save the data to the memory space points to by the parameter BUF, the parameter LEN is the maximum length of the received data. Parameter Flags is typically set 0, please refer to RECV () for other numerical definitions. The parameter from the network address used to specify the network address to be transmitted, and the structure SockAddr refers to Bind (). Parameter from Fromlen is the structure length of SockAddr.

return value

Success returns the number of characters received, and the failure returns -1, and the error is existed in Errno.

error code

Ebadf parameter s non-legitimate Socket Processing code EFault parameters There is a pointer pointing to memory space that cannot be accessed. EnotSock parameter S is a file descriptor, non-socket. EINTR is interrupted by the signal. EAGAIN This action will block the process, but the Socket of the parameter S is not blockable. The Enobufs system's buffer memory is not enough ENOMEM core memory instead of EINVAL. example

/ * Using Socket's UDP Client This program will connect UDP Server and pass the keyboard input to the Server. For the UDP Server example, please refer to Sendto (). * / # include #include #include #include #include #include #include #define port 2345 # Define Server_ip "127.0.0.1" main () {Int S, Len; struct sockaddr_in addr; int addressdr_len = sizeof (struct sockaddr_in); char buffer [256] ; / * Establish Socket * / if ((s = socket, sock_dgram, 0) <0) {PERROR ("socket"); exit (1);} / * Fill in SockAddr_in * / Bzero (& Addr, Sizeof Addr); addr.sin_family = AF_INET; addr.sin_port = htons (port); addr.sin_addr.s_addr = inet_addr (server_ip); While (1) {Bzero (Buffer, sizeof (buffer)); / * From standard input Equipment gets string * / len = read (stdin_fileno, buffer, sizeof (buffer); / * Transferring strings to Server * / sendto (s, buffer, len, 0, & addr, addr_len); / * Receive Server Returned string * / len = recvfrom (s, buffer, sizeof (buffer), 0, & addr, & addr_len; printf ("receive:% s", buffer;}}

carried out

(UDP Server and then execute UDP client) hello / * Enter string from the keyboard * / receive: Hello / * Server end comes back * /

Recvmsg (received data by socket)

related functions

RECV, Recvfrom, Send, Sendto, Sendmsg, Socket

Header file

#include #include

Definition function

INT Recvmsg (int S, Struct Msghdr * MSG, Unsigned Int Flags);

Function description

Recvmsg () is used to receive data from the remote host to the specified Socket. The parameter S is a Socket that has been established, and if the UDP protocol is used, it does not need to be connected. Parameter MSG points to the data structure content of wiring, parameter FLAGS is generally 0, please refer to Send (), please refer to Send (). For the definition of structural MSGHDR, please refer to SendMSG ().

return value

Success returns the number of characters received, and the failure returns -1, and the error is existed in Errno.

error code

Ebadf parameter S non-legitimate Socket processing code. In the EFault parameter, you have a pointer to the unacceptable memory space EnotSock parameter S is a file descriptor, non-socket. EINTR is interrupted by the signal. EAGAIN This action will block the process, but the Socket of the parameter S cannot be blocked. The Enobufs system's buffer memory is not enough ENOMEM core memory instead of EINVAL. example

Refer to RECVFROM ().

Send (via Socket Transfer Data)

related functions

Sendto, Sendmsg, Recv, Recvfrom, Socket

Header file

#include #include

Definition function

INT Send (int LEN, Unsigned Int falgs);

Function description

Send () is used to pass the data by the specified Socket to the other party host. The parameter S is a Socket that has been established. The parameter MSG points to the data content that is wired, and the parameter LEN is the data length. Parameter Flags typically set 0, other values ​​define the data transmitted by the MSG_oob as follows Out-of-Band. MSG_DONTROUTE Cancel Routing Table Query MSG_DONTWAIT Set to Unblable Operation MSG_NOSignal This action is not willing to be interrupted by the SIGPIPE signal.

return value

Success returns the number of characters that actually transmits, and the failure returns -1. Error reason exists in errno

error code

Ebadf parameter S non-legitimate Socket processing code. In the EFault parameter, you have a pointer to the unacceptable memory space EnotSock parameter S is a file descriptor, non-socket. EINTR is interrupted by the signal. EAGAIN This action will block the process, but the Socket of the parameter S cannot be blocked. The Enobufs system's buffer memory is not enough ENOMEM core memory instead of EINVAL.

example

Refer to Connect ()

Sendmsg (Socket Transfer Data)

related functions

Send, Sendto, Recv, Recvfrom, Recvmsg, Socket

Header file

#include #include

Definition function

INT Sendmsg (int S, Const strcut msghdr * msg, unsigned int flags);

Function description

Sendmsg () is used to pass the data by the specified Socket to the other party host. The parameter S is a Socket that has been established, and if the UDP protocol is used, it does not need to be connected. Parameter MSG points to the contents of the data structure to be wired, the parameter Flags is generally default to 0, and please refer to Send (). Structure msghdr defined as follows struct msghdr {void * msg_name; / * Address to send to / receive from * / socklen_t msg_namelen;. / * Length of addres data * / strcut iovec * msg_iov; / * Vector of data to send / receive into * / size_t msg_iovlen; / * Number of elements in the vector * / void * msg_control; / * Ancillary dat * / size_t msg_controllen; / * Ancillary data buffer length * / int msg_flags; / * Flags on received message * /};

return value

Success, return the number of characters actually transmitted, and the failure returns -1, and the error is existed in Errno error code.

Ebadf parameter S non-legitimate Socket processing code. In the EFault parameter, you have a pointer to the unacceptable memory space EnotSock parameter S is a file descriptor, non-socket. EINTR is interrupted by the signal. EAGAIN This action will block the process, but the Socket of the parameter S cannot be blocked. The Enobufs system's buffer memory is not enough ENOMEM core memory instead of EINVAL.

example

Refer to Sendto ().

Sendto (Socket Transfer Data)

related functions

Send, Sendmsg, Recv, Recvfrom, Socket

Header file

#include #include

Definition function

Int Sendto (int LEN, Unsigned Int Flag, Int Len, Unsigned Int Flags, Const Struct SockAddr * To, INT TOLEN);

Function description

Sendto () is used to pass the data from the specified Socket to the other party. The parameter S is a Socket that has been built, and if the UDP protocol is used, it does not need to be operated. The parameter MSG points to the data content of the wiring, the parameter Flags is generally 0, and please refer to Send (). The parameter TO is used to specify the network address to be transferred, and the structure SOCKADDR is referred to BIND (). The parameter TOLEN is the result length of SockAddr.

return value

Success, return the number of characters actually transmitted, the failure returns -1, and the error is existed in Errno.

error code

Ebadf parameter s illegal Socket processing code. There is a pointer in the efault parameter to point to the memory that cannot be accessed. WNOTSOCK CANSHU S is a file description word, non-socket. EINTR is interrupted by the signal. EAGAIN This action will block the process, but the SOKET of the parameter S is blocking. The buffering memory of the Enobufs system is insufficient. The parameters passing to the system call to the system are incorrect.

example

#include #include # include #include #define port 2345 / * port * / main () {Int SockFD, Len; Struct SockAddr_in Addr; Char Buffer [256]; / * Establish Socket * / IF (SockFD = Socket (AF_INET, SOCK_DGRAM, 0) <0) {Perror ("Socket"); EXIT (1) } / * Fill in the sockaddr_in structure * / bzero (& addr); addr.sin_family = AF_INET; addr.sin_port = htons (port); addr.sin_addr = HTON1 (INADDR_ANY); if (Bind (Sockfd, & Addr) , SIZEOF (ADDR) <0) {Perror ("Connect"); exit (1);} while (1) {bezro (buffer, sizeof (buffer); len = recvfrom (socket, buffer, sizeof (buffer) , 0, & addr & addr_len; / * Display the network address of the client * / Printf ("Receive FROM% S / N", INET_NTOA (Addr.sin_ADDR)); / * Return the string to the client * / sendto (sockfd, Buffer, Len, 0, & Addr, AddR_len; "}}

Please refer to Recvfrom ()

SetProtoent (Open the data file of the network protocol)

related functions

GetProtobyname, GetProtobynumber, Endprotoent

Header file

#include

Definition function

Void setProtoent (int Stayopen);

Function description

SetProtoent () is used to open / etc / protocols, if the parameter stayopen value is 1, then the next getProtobyname () or getProtobynumber () will not automatically turn this file.

SetServent (Open the data file of the host network service)

related functions

GetServent, GetServByname, GetServbyport, EndServent

Header file

#include

Definition function

Void setServent (int Stayopen);

Function description

SetServent () is used to open / etc / services, if the parameter StayOpen value is 1, then the next getServByName () or getServByport () will return to the automatic shutdown file.

Setsockopt (Set up Socket Status)

related functions

GetSockopt

Header file

#include #include

Definition function

Int setsockopt (int S, int level, int iptname, const void * optval, socklen_toptlen);

Function description

Setsockopt () is used to set the Socket status specified by the parameter S. The parameter Level represents the network layer that wants to set, which is typically set to SOL_Socket to access the Socket layer. Parameter Optname Represents options to set, with the following values: SO_DEBUG Opening or closing the error mode SO_REUSEADDR Allows the local address to reuse the SOCKET form in the bind () process. SO_ERROR Returns the error reason for the resulting Error Reason for SO_DONTROUTE Do not use routing devices to transmit. SO_BROADCAST uses broadcast mode to transfer SO_SNDBUF Settings Send Temporal Size SO_RCVBUF Set whether the received temporary area SO_KEEPALIVE periodically determines whether the connection has been terminated. SO_OOBINLINE will immediately send it to the standard input device so_linger when it receives OOB data. Make sure data is safe and reliable. parameter

OptVal represents the value set, the parameter OPTLEN is the length of OptVal.

return value

Success returns 0, if there is an error, return -1, the error is existed in Errno.

Additional information

EBADF parameter S is not legal Socket processing code ENOTSOCK parameter S is a file descriptor, non-socketenoprotoopt parameter OptName The option specified is incorrect. Efault Parameters Optval Pointer Pointer to Unrecognized memory space.

example

Refer to GetSockOpt ().

Shutdown (Termination Socket Communication)

related functions

Socket, Connect

Header file

#include

Definition function

INT Shutdown (int S, int how);

Function description

Shutdown () is used to terminate the Socket connection specified by the parameter s. The parameter S is the Socket processing code in the connection. The parameter HOW has the following cases: how = 0 terminates the read operation. How = 1 Termination Transfer Operation How = 2 Terminate Read and Transfer Operation

return value

Success returns 0, failed to return -1, and the error is existed in Errno.

error code

EBADF parameter S is not a valid socket processing code ENOTSOCK parameter S is a file descriptor, the SocketConn parameter s specified Socket is not connected

Socket (create a socket communication)

related functions

Accept, Bind, Connect, Listen

Header file

#include #include

Definition function

INT Socket (int Domain, int type, int protocol);

Function description

Socket () is used to create a new Socket, which is to register to the system, notify the system to establish a communication port. Parameter Domain Specifies what kind of address type, complete definition is within /usr/include/bits/socket.h, is a common protocol: PF_UNIX / PF_LOCAL / AF_UNIX / AF_LOCAL UNIX process communication protocol PF_INET? AF_INET IPv4 Network Protocol PF_INET6 / AF_INET6 Ipv6 network protocol PF_IPX / AF_IPX IPX-Novell protocol PF_NETLINK / AF_NETLINK core user interface device PF_X25 / AF_X25 ITU-T X.25 / ISO-8208 protocol PF_AX25 / AF_AX25 amateur radio AX.25 protocol PF_ATMPVC / AF_ATMPVC access the original ATM PVCsPF_APPLETALK / AF_APPLETALK AppleTalk (DDP) Protocol PF_PACKET / AF_PACKET Junior Packet Interface

parameter

Type has the following values: Sock_Stream provides two-way continuous and trusted data streams, namely TCP. Support OOB mechanisms, you must use Connect () to establish a connection status before all data transfer. SOCK_DGRAM Connection Sock_seqpacket provides continuously reliable packet connection SOCK_SEQPACKET to provide SOCK_RAW to provide raw network protocol Access SOCK_RDM to provide a trusted packet connection SOCK_PACKET Provider to communicate directly to the network driver. Protocol is used to specify the transfer protocol number used by the socket, usually this reference does not need to be used, set to 0. return value

Success returns the socket processing code, failed to return -1.

error code

EPROTONOSUPPORT Parameter Domain Specifies the type of Type or Protocol, which is not supported, the core memory is insufficient, and unable to establish a new Socket structure Emfile process file table overflow, unable to establish a new SocketeAccess permission, unable to establish a Type or protocol specified protocol ENOBUFS / ENOMEM insufficient einval parameter Domain / Type / protocol is not legal

example

Refer to Connect ().

GetENV (acquired environment variable content)

related functions

Putenv, SetENV, UNSETENV

Header file

#include

Definition function

Char * getenv (const char * name);

Function description

GetENV () is used to obtain the content of the parameter Name environment variable. The parameter name is the name of the environment variable, and if the variable is present, the pointer to which the content is returned. The format of the environment variable is name = value.

return value

Returns NULL returns a pointer to the content to return to NULL.

example

#include mian () {char * p; if ((p = getenv ("user")))) Printf ("User =% S / N", P);}

carried out

User = root

Putenv (changing or increasing environment variable)

related functions

GetENV, STENV, UNSETENV

Header file

# include4

Definition function

INT PUTENV (Const Char * String);

Function description

Putenv () is used to change or increase environment variables. The format of the parameter String is name = value, if the environment variable is originally existing, the variable content changes according to the parameter String, otherwise the contents of this parameter will become new environment variables.

return value

If the execution is successful, it returns 0, and there is an error to return -1.

Getopt (Analyze command line parameters)

related functions

Header file

#include

Definition function

INT Getopt (int Argc, char * const argv [], const char * optstring;

Function description

Getopt () is used to analyze command line parameters. The parameters argc and argv are the number and content of the parameters passed by main (). Parameters OPTString represents the option string that wants to process. This function returns an option letter in Argv in the ARGV, and this letter will correspond to the letter in the parameter OPTSTRING. If the letter in the hook string is then colon ":", it means that there is also related parameters, and the whole variable OPTARG will point to this extra parameter. If getopt () can't find the matching parameter, the error message is printed, and set the whole variable Optopt to "?" Characters, if you do not want GetOpt () printing error message, just set the whole domain variable OpterR to 0.

return value

If you find a match, you return this parameter, if the parameter is not included in the parameter OPTString option letter returns "?" Characters, the analysis is over -1. example

#include #include int main (int argc, char ** argv) {int CH; opTerr = 0; while ((ch = getopt (argc, argv, "a: bcde") )! = -1) Switch (CH) {CASE 'A': Printf ("Option A: '% S' / N", OPTARG); Break; Case 'B': Printf ("Option B: B / N" Break; Default: Printf ("Other Option:% C / N", CH);} Printf ("Optopt % C / N", Optopt);

carried out

$. / GETOPT -BOPTION B: B $. / GETOPT -COTHER OPTION: C $. / getopt -aother option:? $. / getopt -a12345option A: '12345'

Isatty (determining if the file description word is a terminal)

related functions

TTYNAME

Header file

#include

Definition function

INT isatty (int desc);

Function description

If the file description word represented by the parameter DESC is returned to 1, otherwise it returns 0.

return value

Returns 1 if the file is a terminal, otherwise it returns 0.

example

Refer to TTYNAME ().

SELECT (I / O multi-work mechanism)

Header file

#include #include #include

Definition function

INT SELECT (int N, fd_set * readfds, fd_set * writefds, fd_set * exceptfds, struct timeval * timeout);

Function description

SELECT () is used to wait for a change in the file description. Parameter N represents the largest file description word plus 1, parameters readfds, writefds, and ExceptFDs are called description phrases, is used to return to read, write or exceptions to this descriptive word. The macro under the bottom provides the way these three ways of describing the phrase: fd_clr (INR FD, FD_SET * SET); used to clear the bit fd_isset (int FD, fd_set * set) used in the descriptor set set; used to test the descriptor The bit in the set of the associated FD is true fd_set (int FD, fd_set * set); used to set the bit fd_zero (fd_set * set) of the related FD in the word group set; used to clear all the bit of the descriptor set

parameter

Timeout is the structure TimeVal used to set the wait time for select (), which is defined as the following struct timeval {time_t tv_sec; time_t tv_usec;};

return value

If the parameter timeout is set to NULL, SELECT () is not TIMEOUT.

error code

If the execution is successful, the number of file descriptive words has changed. If it returns 0 represents more than timeout time before the description word status changes, return -1 when there is an error occurs, the error is existed, the parameter readfds, WriteFDS, ExcePTFDS and Timeout values ​​become unpredictable. Ebadf file Description Word is invalid or the file has been closed EINTR This call is interrupted by the signal. The EINVAL parameter N is negative. ENOMEM core memory is insufficient

example

Common program fragment: fs_set readset; fd_zero (& readset); fd_set (fd, & readset); SELECT (fd 1, & readset, null, null, null); if (fd_isset (fd, readset) {...} TTYNAME (Return First terminal name)

related functions

Isatty

Header file

#include

Definition function

Char * TTYNAME (INT DESC);

Function description

If the file description word represented by the parameter DESC is the final machine, the terminal name is returned by a string pointer, otherwise Null.

return value

If success, returns a string pointer to the terminal name, and NULL is returned when there is an error condition.

example

#include #include #include #include main () {int fd; char * file = "/ dev / tty"; FD = Open (Fiel, o_rdonly); Printf ("% s", file); if (isatty (fd)) {printf ("is a tty./n" );printf ("tyname =% s / n", TTYNAME (FD)); Else Printf ("is not a tty / n"); Close (fd);}

carried out

/ dev / tty is a TTYTTYNAME = / dev / tty

转载请注明原文地址:https://www.9cbs.com/read-99516.html

New Post(0)