C70. C String I/O


String I/O
The functions described in this section are a bit unusual, since they have nothing to do with streams or tiles. Instead, they allow us to read and write data using a string as though it were a stream. The sprintf and snprintf functions write charac­ters into a string in the same way they would be written to a stream; the sscanf function reads characters from a string as though it were reading from a stream. These functions, which closely resemble printf and scanf, are quite useful, sprintf and snprintf give us access to printf's formatting capabilities without actually having to write data to a stream. Similarly, sscanf gives us access to scanf's powerful pattern-matching capabilities.
Three similar functions (vsprintf, vsnprintf, and vsscanf) also belong to . However, these functions rely on the va_list type, which is declared in .

Output Functions
int sprintf(char * restrict s,const char * restrict format,..);
int snprintf(char * restrict s, sizet n, const char * restrict format,..);
The sprintf function is similar to printf and fprintf. except that it writes output into a character array (pointed to by its first argument) instead of a stream, sprintf \s second argument is a format string identical to that used by printf and fprintf.

sprintf has a variety of uses. For example, we might occasionally want to format data for output without actually writing it. We can use sprintf to do the formatting, then save the result in a string until it's time to produce output, sprintf is also convenient for converting numbers to character form.
The snprintf function is the same as sprintf, except for the additional parameter n. No more than n - 1 characters will be written to the string, not count­ing the terminating null character, which is always written unless n is zero. (Equiv-laiently, we could say that snprintf writes at most n characters to the string, the last of which is a null character.) .

snprintf returns the number of characters that would have been written (not including the null character) had there been no length restriction. If an encod­ing error occurs, snprintf returns a negative number. To see if snprintf had room to write all the requested characters, we can test whether its return value was nonnegative and less than n.



Input Functions
int sscanf(const char * restrict s,const char * restrict format, ...);
The sscanf function is similar to scanf and fscanf. except that it reads from a string (pointed to by its first argument) instead of reading from a stream, sscanf's second argument is a format string identical to that used by scanf and fscanf.
sscanf is handy for extracting data from a string that was read by another input function. For example, we might use fgets to obtain a line of input, then pass the line to sscanf for further processing:
fgets(str, sizeof(str), stdin); /* reads a line of input */
sscanf(str, "%d%d", &i, &j); /* extracts two integers */
One advantage of using sscanf instead of scanf or fscanf is that we can examine an input line as many times as needed, not just once, making it easier to recognize alternate input forms and to recover from errors.

Library Support for Numbers and Character Data
This chapter describes the five most important library headers that provide support for working with numbers, characters, and character strings. the and headers, which contain macros describing the characteristics of numeric and character types. the cmath. h> header, which provides mathematical functions. and headers, which provide character functions and string functions, respectively.

C99 adds several headers that also deal with numbers, characters, and strings. The and ,, , cinttypes. h>, , and .

The Header: Characteristics of Floating Types
The header provides macros that define the range and accuracy of the float, double, and long double types. There are no types or functions in .

Two macros apply to all floating types. The FLT_ROUNDS macro represents the current rounding direction for floating-point addition.

Value
Meaning
-1
Indeterminable
0
Toward zero
1
To nearest
2
Toward positive infinity
3
Toward negative infinity

Unlike the other macros in , which represent constant expressions, the value of FLT_ROUNDS may change during execution. (The fesetround function allows a program to change the current rounding direction.) The other macro, FLT_RADIX, specifies the radix of exponent representation; it has a mini­mum value of 2 (indicating binary representation).

The remaining macros, which I'll present in a series of tables, describe the characteristics of specific types. Each macro begins with either FLT, DBL, or LDBL, depending on whether it refers to the float, double, or long double type. The C standard provides extremely detailed definitions of these macros; my descriptions will be less precise but easier to understand. The tables indicate maxi­mum or minimum values for some macros, as specified in the standard.

BelowTable  lists macros that define the number of significant digits guaranteed by each floating type.
Name
Value
Description
FLT_ ANT_DIG

Number of significant digits (base FLT _RADIX)
DBL_MANT DIG


LDBL_MANT_DIG


FLT_DIG
DBL_DIG LDBL_DIG
>6
>10
 >10
Number of significant digits (base 10)


The Header: Sizes of Integer Types
The header provides macros that define the range of each integer type (including the character types), declares no types or functions.
One set of macros in deals with the character types: char, signed char, and unsigned char.
The other macros in deal with the remaining integer types: short int, unsigned short int, int, unsigned int, long int, etc..


The Header (C89): Mathematics
The functions in the C89 version of fall into five groups:
Trigonometric functions Hyperbolic functions Exponential and logarithmic functions Power functions Nearest integer, absolute value, and remainder functionsC99 adds a number of functions to these groups as well as introducing other cate­gories of math functions. The C99 changes to are so extensive that I've chosen to cover them in a separate section that follows this one. That way, readers who are primarily interested in the C89 version of the header—or who are using a compiler that doesn't support C99 won't be overwhelmed by all the C99 additions.
The math header defines several mathematic functions.
Macros:
HUGE_VAL
Functions:
acos();
asin();
atan();
atan2();
ceil();
cos();
cosh();
exp();
fabs();
floor();
fmod();
frexp();
ldexp();
log();
log10();
modf();
pow();
sin();
sinh();
sqrt();
tan();
tanh();

C Library Functions

String Manipulation Functions

char *strcpy (char *dest, char *src);
Copy src string into dest string.

char *strncpy(char *string1, char *string2, int n);
Copy first n characters of string2 to stringl .

int strcmp(char *string1, char *string2);
Compare string1 and string2 to determine alphabetic order.

int strncmp(char *string1, char *string2, int n);
Compare first n characters of two strings.

int strlen(char *string);
Determine the length of a string.

char *strcat(char *dest, const char *src);
Concatenate string src to the string dest.

char *strncat(char *dest, const char *src, int n);
Concatenate n chracters from string src to the string dest.

char *strchr(char *string, int c);
Find first occurrence of character c in string.

char *strrchr(char *string, int c);
Find last occurrence of character c in string.

char *strstr(char *string2, char string*1);
Find first occurrence of string string1 in string2.

char *strtok(char *s, const char *delim) ;
Parse the string s into tokens using delim as delimiter.
Memory Management Functions

void *calloc(int num elems, int elem_size);
Allocate an array and initialise all elements to zero .

void free(void *mem address);
Free a block of memory.

void *malloc(int num bytes);
Allocate a block of memory.

void *realloc(void *mem address, int newsize);
Reallocate (adjust size) a block of memory.
Buffer Manipulation

void* memcpy(void* s, const void* ct, int n);
Copies n characters from ct to s and returns s. s may be corrupted if objects overlap.

int memcmp(const void* cs, const void* ct, int n);
Compares at most (the first) n characters of cs and ct, returning negative value if csct.

void* memchr(const void* cs, int c, int n);
Returns pointer to first occurrence of c in first n characters of cs, or NULL if not found.

void* memset(void* s, int c, int n);
Replaces each of the first n characters of s by c and returns s.

void* memmove(void* s, const void* ct, int n);
Copies n characters from ct to s and returns s. s will not be corrupted if objects overlap.
Character Functions

int isalnum(int c);
The function returns nonzero if c is alphanumeric

int isalpha(int c);
The function returns nonzero if c is alphabetic only

int iscntrl(int c);
The function returns nonzero if c is a control chracter

int isdigit(int c);
The function returns nonzero if c is a numeric digit

int isgraph(int c);
The function returns nonzero if c is any character for which either isalnum or ispunct returns nonzero.

int islower(int c);
The function returns nonzero if c is a lower case character.

int isprint(int c);
The function returns nonzero if c is space or a character for which isgraph returns nonzero.

int ispunct(int c);
The function returns nonzero if c is punctuation

int isspace(int c);
The function returns nonzero if c is space character

int isupper(int c);
The function returns nonzero if c is upper case character

int isxdigit(int c);
The function returns nonzero if c is hexa digit

int tolower(int c);
The function returns the corresponding lowercase letter if one exists and if isupper(c); otherwise, it returns c.

int toupper(int c);
The function returns the corresponding uppercase letter if one exists and if islower(c); otherwise, it returns c.
Error Handling Functions

void perror(const char *s);
produces a message on standard error output describing the last error encountered.

char *strerror(int errnum );
returns a string describing the error code passed in the argument errnum.

No comments: