Description of common functions in C language

Source: Internet
Author: User
Tags function prototype strcmp strtok

1. Prototype declaration: Char *strcpy (char* dest, const char *SRC);

Header files: #include <string.h> and #include <stdio.h>

Function: Copy a string that starts from the SRC address and contains a null terminator to the address space starting with dest

Description: The memory areas referred to by SRC and dest cannot overlap and dest must have sufficient space to accommodate the SRC string.

Returns a pointer to the dest.

char* strcpy (char* des,const char* Source)

{

char* R=des;

ASSERT ((des! = null) && (source = null));

while ((*des++ = *source++)! = ' + ');

return R;

}

/*while ((*des++=*source++)); Explanation: The assignment expression returns the left operand, so the loop stops after the assignment of NULL */


2, Function prototype: char*strncpy (CHAR*DEST,CHAR*SRC,SIZE_TN);

Feature editing (c/d + +) copies the contents of the string src (characters, numbers, kanji ...). ) to the string dest, the number of copies is determined by the value of Size_tn.

If the first n bytes of Src do not contain a null character, the result does not end with a null character. If the src length is less than n bytes, the dest is padded with null until n bytes are copied.

The memory areas referred to by SRC and dest cannot overlap and dest must have enough space to accommodate the SRC character length + '. '

Difference:

(1) strcpy only copies the string, but does not limit the number of copies, it can easily cause buffer overflow. strncpy be a little safer.

(2) strncpy can select a character output, strcpy can not


3, function prototype: Char *strcat (char *dest,char *src);

Function: Add the string of SRC to the end of the dest ("\" At the end of the dest) and add '/'.

Description: The memory areas referred to by SRC and dest cannot overlap and dest must have sufficient space to accommodate the SRC string.

Returns a pointer to the dest.


4. Function prototype: Char *strncat (char *dest,char *src,int N)

Parameter description: SRC is the source string, Dest is the destination string, and N is the first n characters in the specified SRC.

Library Name: #include <string.h>

function function: Add the first n characters of the string src refers to the end of the dest, overwriting the '/0 ' at the end of the dest to implement a string connection.

Return Description: Returns a pointer to the concatenated string.


5. Function prototype: extern char *strstr (char *str1, const char *STR2);

Syntax: * STRSTR (STR1,STR2)

STR1: The target string expression to search is searched.

STR2: To find the object, the string expression to find.

return value: If STR2 is a substring of str1, returns the address of the first occurrence of str2 in str1, or null if STR2 is not a substring of str1.


6. Function prototype: char *STRCHR (const char* _str,int _val)

Char *strchr (char* _str,int _ch)

Header files: #include <string.h>

Function: Finds the first occurrence of the character C in the string s

Description: Returns a pointer to the position of the first occurrence of C, the address returned is the first pointer to the same character as Val at the beginning of the lookup string pointer, and returns NULL if there is no C in S.

Return value: Success returns the position to find the first occurrence of the character, failure returns null


7, function prototype: char *STRRCHR (const char *STR, char c);

Owning Library: string.h

function function: Find a character C in another string str in the last occurrence of the position (that is, starting from the right side of STR to find the first occurrence of the character C position), and

Returns the address of this location. If the specified character cannot be found, then the function returns NULL.


8. Function prototype: extern int strcmp (const char *s1,const char *S2);

When S1<S2, returns a negative number

When s1=s2, return value = 0

Returns a positive number when S1>S2

That is: two strings are compared from left to right by character (by the ASCII value size) until different characters are present or "s" is encountered. Such as:

"A" < "B" "a" > "a" "Computer" > "Compare"

Special NOTE: strcmp (const char *s1,const char * s2) can be used to compare two string constants in a string.

or compare arrays and string constants, you cannot compare other forms of parameters such as numbers. The ANSI standard specifies that the return value is positive, negative, 0.

The exact value is dependent on the different C implementations.


9, function prototype: extern int stricmp (char *s1,char * s2);

Features: Compares strings S1 and S2, but does not differentiate between uppercase and lowercase letters.

Description: Strcmpi is a macro definition to stricmp and does not actually provide this function.

When S1<s2, the return value <0

When S1=s2, the return value =0

When S1>s2, the return value >0

You can use functions such as _stricmp to handle string-case insensitivity in C + +.


10. Function prototype: int strncmp (const char *, const char *, size_t);

Function: This function is used to compare the first maxlen characters of S1 and S2 strings. If two strings are equal, STRNCMP will return 0.

If S1 is a substring of S2, S1 is less than S2. Also, function int strncmp (const char *S1, const char *S2, size_t size) This function is very similar to strcmp.

The difference is that the STRNCMP function is a specified comparison of size characters. That is, if the string S1 is the same as the first size character of S2, the function returns a value of 0.


11, function prototype: extern unsigned int strlen (char *s);

Function: Calculates the length of the given string (unsigned int), excluding '

Description: Returns the length of S, excluding the Terminator null.


12, Function prototype: strtok (char *s, const char *delim);

Function: Decomposes a string into a set of strings. S is the character to be decomposed, and the Delim is a delimiter character (in the case of a string, the first is the split criterion).

Strtok () is used to split a string into fragments. The parameter S points to the string to be split, and the parameter Delim all characters contained in the split string.

When Strtok () finds the split character contained in the parameter Delim in a string of parameter s, the character is changed to the \ s character.

At the first call, Strtok () must give the parameter S string, and the subsequent call sets the parameter s to null. Each successful call returns a pointer to the segmented fragment.

Return value: A segmented string starting with the beginning of S. Null is returned when a character in Delim is not found.

All the characters contained in the Delim will be filtered out and set to a segmented node where the filter is removed.


13. Function prototype: void *memmove (void* dest, const void* SRC, size_t count);

Header file:<string.h>

Function: the memory area referred to by SRC is copied from count bytes to the memory area of Dest.


14. Function prototype: void *memset (void *s, int ch, size_t n);

Function Explanation: Replace the first n bytes in s (typedef unsigned int size_t) with CH and return S.

Memset: The effect is to populate a block of memory with a given value, which is the fastest way to clear 0 operations on a larger struct or array.


15. Function prototype: void *memcpy (void *dest, const void *SRC, size_t n);

Function: Copies n bytes from the starting position of the memory address referred to by the source SRC to the beginning of the memory address referred to by the target dest.

Return value: The function returns a pointer to Dest.

Description

(1) The memory areas referred to by source and Destin may overlap, but if the memory areas referred to by source and Destin overlap, this function does not ensure that the overlapping area of the source is not overwritten before the copy.

The use of memmove can be used to process overlapping areas. The function returns a pointer to Destin.

(2) If the target array Destin itself already has data, after executing memcpy (), the original data (up to N) will be overwritten.

If you want to append data, add the destination array address to the address you want to append the data to after each execution of memcpy.

Note: Both source and Destin are not necessarily arrays, and any readable and writable space is available.


16. Function prototype: int memcmp (const void *BUF1, const void *BUF2, unsigned int count);

Function: Compares the memory area BUF1 and the first count bytes of buf2.

When Buf1<buf2, the return value <0

When Buf1==buf2, the return value =0

When Buf1>buf2, the return value >0

Description: The function is compared by byte.

For example:

S1,S2 is a string when memcmp (s1,s2,1) is the first byte of the comparison S1 and S2 ASCII code value;

MEMCMP (s1,s2,n) is the ASCII code value comparing the first n bytes of S1 and S2;


17, function prototype: int scanf (const char *format,...);

The function scanf () is a generic subroutine that reads content from the standard input stream stdio (standard input device, usually the keyboard), reads multiple characters in a format that can be described, and saves them in the corresponding address variable.

Its invocation form is: scanf ("< format description string >",< variable address >), variable address requirements are valid, and the order of the format description is consistent.

It is a format input function that enters data into the specified variable from the keyboard, in the format specified by the user.

Return value: the scanf () function returns the number of data items that were successfully assigned, and EOF is returned when there is an error reading the end of the file.


18. Function prototype: extern void printf (const char *format,...);

Function: A function that produces formatted output in C (defined in stdio.h), which outputs characters to the terminal (display, console, and so on).

The printf () function is called in the format: printf ("< formatted string >", < Parameter table >).

Description: The printf () function is a formatted output function that is typically used to output information to a standard output device in a prescribed format.

Format output, which is a function (defined in stdio.h) that produces formatted output in the C language. Used to output characters to a terminal (display, console, and so on). Format control consists of text and data format descriptions to be output.

In addition to using letters, numbers, spaces, and some number symbols, you can use some escape characters to represent special meanings in the text you want to output.


19. Function prototype int snprintf (char *str, size_t size, const char *format, ...) ;

Function: Variable parameter (...) Formats the string as format and then copies it to Str

(1) If the string length < size is formatted, copy the string to str and add a string terminator (' + ') to it;

(2) If the formatted string length >= size, only the (size-1) characters are copied to STR, followed by a string terminator (' + '), and the return value is the length of the string to be written.

function return value: Returns the length of the string to be written if successful, or a negative value if an error occurs.


20. Function prototype: int sscanf (const char *, const char *, ...);

Description: SSCANF is similar to scanf, which is used for input, except that the latter takes the keyboard (stdin) as the input source, the former with a fixed string as the input source.

Common usage:

Char buf[512];

SSCANF ("123456", "%s", buf);//Here buf is the name of the array, which means to deposit 123456 in buf in the form of%s!

printf ("%s\n", buf);

The result is: 123456


21. Function Prototype: FILE * fopen (const char * path,const char * mode);

Return value: The file pointer to the stream will be returned when the file is opened successfully. Returns null if the file fails to open, and the error code exists in errno.

In general, after opening the file will do some file read or write action, if the file fails to open, the next read and write actions will not be smooth, so generally after fopen () for error judgment and processing.

Parameter description:

The parameter path string contains the file path and filename to open, and the parameter mode string represents the flow pattern.

Mode has the following pattern strings:

R opens the file as read-only, and the file must exist.

r+ Open the file as read-write, the file must be present.

rb+ Read and write open a binary file that allows read and write data, and the file must exist.

W Open Write-only file, if the file exists then the file length is clear to 0, that is, the contents of the file will disappear. If the file does not exist, the file is created.

w+ Open a read-write file, if the file exists then the file length is clear to zero, that is, the contents of the file will disappear. If the file does not exist, the file is created.

A write-only file opens in an additional way. If the file does not exist, the file will be created, and if the file exists, the data written will be added to the end of the file, that is, the original content of the file will be retained. (EOF character reserved)

A + opens readable and writable files in an additional way. If the file does not exist, the file will be created, and if the file exists, the data written will be added to the end of the file, that is, the original content of the file will be retained. (the original EOF character is not preserved)

WB only writes Open or create a new binary file; Only write data is allowed.

wb+ read-write open or create a binary file that allows reading and writing.

ab+ Read and write open a binary file that allows you to read or append data at the end of the file.

WX creates a text file that allows only data to be written. [C11]

WBX creates a binary file that only allows data to be written. [C11]

W+x creates a text file that allows read and write. [C11]

Wb+x creates a binary file that allows read and write. [C11]

W+BX and "wb+x" are the same [C11]

The pattern ending in X is exclusive, the file already exists or cannot be created (usually the path is incorrect), which causes fopen to fail. The file is opened in exclusive mode supported by the operating system.

Common usage:

{file*fp=null;//need to be aware

Fp=fopen (F_path, "R");

if (NULL==FP)

return-1;//to return an error code

Fclose (FP);

fp=null;//needs to point to null, otherwise it will point to the original open file address}


22, function prototype: Char *fgets (char *buf, int bufsize, FILE *stream);

Parameters:

*BUF: A character pointer that points to the address used to store the resulting data.

BufSize: Integer data indicating the size of the stored data.

*stream: File structure pointer, the file stream that will be read.

Description

Reads data from the file structure pointer stream, reading one row at a time. The data read is stored in an array of characters pointed to by BUF, reading up to bufsize-1 characters at a time (bufsize assigned ' + '),

If the line in the file is less than bufsize characters, the line finishes reading. If the number of characters in the line (including the last newline character) exceeds bufsize-1, then fgets only returns an incomplete row.

However, the buffer always ends with a null character, and the next call to Fgets continues to read the row. The function succeeds in returning BUF, failing or reading to the end of the file, returning null.

Therefore, we cannot judge whether a function is terminated by an error directly through the return value of fgets, and should be judged by feof function or Ferror function.


23, function prototype: int fputs (int, FILE *);

Description: Fputs is a function that has the function of writing a string to the specified file (does not automatically write the string end tag ' \ s ').

When a string is successfully written, the position pointer of the file is automatically moved back, the function returns a non-negative integer, or EOF (the symbolic constant, whose value is-1) is returned.

Common usage:

{charstr[80]= "I/osystem."; * String constants are stored in the character array */

FILE*FP; /* Define file pointer fp*/

if ((Fp=fopen ("Strfile", "W")) ==null)/* Open File Write mode */

{

printf ("cannotopenthefile.\n")/* Determine if the file is open correctly */

Exit (0);

}

Fputs (STR,FP);/* Writes a string to a file */

Fclose (FP);/* Close file */}


24. function format: int FPUTC (char C, File *FP)

Parameter interpretation: FP is a file pointer, and its value is obtained when executing fopen () Open file.

n is the amount of characters for the output.

Although the function is defined as an integer, it is only eight bits lower.

return value: In normal invocation, the function returns the ASCII value of the character written to the file, and when an error occurs, it returns EOF (-1). When a character or a byte of data is written correctly, the internal write pointer of the file is automatically moved back one byte to the position.

EOF is a macro defined in the header file stdio.h.

Common usage:

{file*f;

Char*s= "hey,buddy!";

int i;

F=fopen ("MyFile.txt", "w");

For (I=0;i<strlen (s); i++)

FPUTC (S[I],F);

Fclose (f);}


25, function prototype: int fgetc (FILE *stream);

Function Description: fgetc () reads a character from the file referred to in the parameter stream and returns it as a character. If you read the end of the file or if there is an error, it returns EOF, and you must differentiate between the two cases by ferror or feof.

return value: Fgetc () returns the read character, or the end of the file if EOF is returned, or an error occurred.

Case:

{FILE *FP;

int C;

Fp=fopen ("exist", "R");

while ((C=FGETC (FP))!=eof)

printf ("%c", c);

Fclose (FP);}


26, function prototype: int feof (FILE *stream);

Function: Detects the file terminator on the stream, returns a value other than 0 if the file ends, otherwise returns 0, and the file terminator can only be cleared by Clearerr ().

EOF is a sign of the end of a text file. In a text file, the data is stored in the form of a character's Ascⅱ code value, the Ascⅱ code of the normal character is from 32 to 127 (decimal), and the EOF 16 is 0xFF (decimal-1), so you can use EOF as the end-of-file flag.

Case:

{if (feof (stream))

printf ("We have reached end of file\n");}

27, function prototype: int ferror (FILE *stream);

Description: ferror, function name, in the invocation of various input and output functions (such as putc.getc.fread.fwrite, etc.), if an error occurs, in addition to the function return value reflects, you can also be checked with the Ferror function.

Its general invocation form is ferror (FP), and if the Ferror return value is 0 (false), no error is expressed. If a non-0 value is returned, an error is expressed. It should be noted that each time the input and output function is called on the same file,

All produce a new value for the Ferror function, so you should check the value of the Ferror function immediately after invoking an input-output function, otherwise the information will be lost. The initial value of the Ferror function is automatically set to 0 when the fopen function is executed.

Case:

{if (ferror (stream))/*testforanerroronthestream*/

printf ("Error reading from file\n");}


28, function prototype: int fflush (FILE *stream);

Function: Clears the read-write buffer and requires the data of the output buffer to be physically written to immediately.

Return value: Fflush returns 0 if the refresh is successful. The specified stream also returns a value of 0 when there is no buffer or read-only open. Return EOF indicates an error.

Note: If Fflush returns EOF, the data may have been lost due to a write error. When setting up a critical error handler, it is safest to use the SETVBUF function to close the buffer or use a low-level i/0 routine, such as open, close, and write instead of the stream I/O function.

Case:

{/*flushthestream ' sinternalbuffer*/

Fflush (stream);}


29, function prototype: int fclose (FILE *stream);

Fclose is a function name that closes a stream. Note: Using the fclose () function, you can output the last remaining data in the buffer to the kernel buffer and release the file pointer and the associated buffer.

Return value: If the stream is closed successfully, FCLOSE returns 0, otherwise EOF (-1) is returned. (if the stream is null and the program can continue execution, fclose sets the error number to EINVAL and returns EOF.) )


30. Function prototype: size_t fread (void *buffer, size_t size, size_t count, FILE *stream);

Parameters

buffer--the memory address used to receive data

size--the number of bytes per data item to read, in bytes

count--to read count data items, each data item is a size byte.

stream--input Stream

Return value: The number of elements actually read. If the return value is not the same as count, the end of the file or an error may occur. Gets the error message from Ferror and feof or detects whether the end of the file is reached.

Case:

{/*readthedataanddisplayit*/

Fread (Buf,strlen (msg) +1,1,stream);

printf ("%s\n", buf);}

31. Function prototype: int fscanf (FILE *, const char *, ...);

Function: Performs a formatted input from a stream, fscanf encounters a space and ends with a newline, and the space is also closed. This differs from Fgets, where fgets encounters a space that does not end.

Return value: Integer, returns the number of parameters read in successfully, and the failure returns EOF (-1).









Common Format Character Description:

%d: Read in a decimal integer.

%i: Read in decimal, octal, hexadecimal integer, similar to%d, but at compile time by data pre-or post-set to differentiate the system, such as "0x" is hexadecimal, adding "0" is octal. For example, the string "031" will be counted as 31 when using%d, but will count as 25 when using%i.

%u: Read in an unsigned decimal integer.

%f%f%g%g: Used to enter real numbers, which can be entered in decimal or exponential form.

%x%x: Read in hexadecimal integer.

%o ': Reads in an octal integer.

%s: Read in a string, and the null character ' \ s ' ends.

%c: Read in a character. Cannot read null value. Spaces can be read into.


Description of common functions in C language

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.