C Programming Language (2nd edition • New version) Chapter 7th input and output

Source: Internet
Author: User
Tags error handling mathematical functions natural logarithm terminates

Input and output are not part of the C language itself. This chapter describes the standard library , focusing on input/output, and introduces string processing, storage management, and mathematical functions;

The ANSI standard defines these library functions precisely, so any system that can use C has a compatible form of these functions, and if the system interaction part of the program uses only the functionality provided by the standard library, it can be ported from a system without modification to the other;These library functions have attributes declared in more than 10 header files, respectively. Appendix B provides a detailed description of the standard library. 7.1 Standard input/outputThe standard library implements a simple text input/output mode; the text stream consists of a series of lines, and each line ends with a newline character (if the system does not follow this pattern, the standard library will make the system adapt to this mode at both the input and output)The simplest input mechanism :   int GetChar (void)//From standard input (usually keyboard)To read and return the next input character or EOF (indicating to the end of the file, defined in <stdio.h>, typically-1)in many environments, you can use symbol < to implement input redirection , such as using GetChar in program prog, the command line:Prog <infile will allow prog to read data from the input file infile (not the keyboard);if the input passes through the pipeline mechanism from another program, then this input is not visible; For example, on some systems, the following command line:Otherprog | Prog will run two programs and redirect Otherprog's standard output through the pipeline to prog standard input; int putchar (int)//putchar (c) sends the character C to standard Output (default is screen display), an error occurred returning Eof;prog >outfile//command line, redirecting standard output from prog to outfileThe function printf also outputs data to the standard output device, and in the program it is possible to cross-call both, and the output is produced sequentially;each source program file that uses the input/output library functions must contain the following statements before referencing these functions:#include <stdio.h>When the file name is enclosed in a pair of angle brackets, the preprocessor locates the specified file (defined by the specific implementation, such as a file in the Unix system, typically in the directory/user/include);Many programs read only one input stream and output to only one output stream, which is sufficient to use only GetChar, Putchar, and printf, especially if you are connecting two programs with a redirect, just using these functions is sufficient;The "functions" in the header file, such as GetChar, Putchar, and ToLower, are generally macros (Section 8.5 describes their implementation), thus avoiding the overhead of making function calls to each character, regardless of the machine, the use of these functions do not need to understand the character set;7.2 Format Output-printf functionprintf converts an internal value into a character form, and the following is only typical usage;int printf (char *format, arg1, arg2, ...)in the output format control, the parameters are converted and formatted, and printed on the standard output device, the return value is the number of characters printed;the format string consists of two types of objects: ordinary characters and conversion descriptions ; Normal characters are copied directly to the output stream; The conversion description starts with a% and ends with a conversion character, which can contain:   • The minus sign//specifies that the converted parameters are output in left-aligned format • Number//designation Minimum Field width, extra character positions are filled with spaces • decimal point//Field width and precision are separated • Number//designation accuracy, which is the maximum number of characters to be printed by the string, the number of digits of the least integer output, the number of digits after the decimal point, the letter H, or L//which prints the integer as short, the latter as a long Basic Conversion Description of the printf function (including all conversion characters):   The int type can be output in the form of decimal (d,i), unsigned octal (o), unsigned hexadecimal (x,x), unsigned decimal (u), single character (c), char * type (s): Print the string sequentially until it encounters '/' or satisfies the accuracy requirement; The double type can be in decimal decimal (f, the default is 6), scientific notation (e,e, precision defaults to 6), choose the format (g,g, I take the name, the exponent is less than 4 or >= precision with E, otherwise the same as F) and other forms to output; void * Type (P): pointer, Depends on the specific implementation;%: Do not convert characters, print a percent semicolonFor example,%-15.10s will produce left-aligned, a minimum of 15 field widths, and a maximum of 10 characters;The width or precision in the conversion description can be represented by an asterisk *, whose value is calculated by converting the next parameter (must int); For example:printf ("%.*s", Max, s); Print up to max characters from a stringThe printf function uses its first parameter to determine the number and type of subsequent arguments, and does not correspond to produce incorrect results; for example:printf (s); If the string s contains%, the output will go wrong with printf ("%s", s); correct int sprintf (char *string, Char *format, arg1, arg2, ...)The function stores the output in a string (not output to standard output); Note that the string size must be sufficient to store the output7.3 Variable length parameter tableExample: The simplest version of printf , which describes how to write a function that can handle a variable-length parameter table in a portable manner. the correct way to declare printf:int printf (char *fmt, ...)the ellipsis (which can only appear at the tail of the parameter table) indicates that the number and type of parameters in the parameter table are variable;The key to this example is to handle a parameter table that does not even have a name:The standard header file <stdarg.h> contains a set of macros that define how to traverse the parameter table , which is used in this example to declare a variable AP (which is a "parameter pointer"), which must be called before using the AP va_list Va_ Start (AP, FMT) Initializes the AP to a pointer to the first unnamed parameter, (the parameter table must include at least 1 well-known parameters, Va_start the last known parameter as the starting point)You also need to call the function va_arg, enter the AP and a type name (such as int, double, char *, to determine the type of the returned object and the length of the pointer movement), it returns a parameter, and the AP refers to the next parameter;The Va_end (AP) must be called before the function returns to complete some necessary cleanup work;7.4 Formatting input-scanf functionsdescribes only some of the most useful features of this function. Also has a variable-length parameter table:int scanf (char *format, ...)The scanf reads a sequence of characters from the standard input, interprets it according to the format description in format, and saves the result to the rest of the arguments (which must be pointers), or when the format string is scanned, or if the input cannot match the format control description, the function terminates The return value is the number or EOF of the entry that successfully matched and assigned a value (note that it is different from 0); The next call to the SCANF function will continue searching from the next character of the last character of the previous conversion;int sscanf (char *string, Char *format, arg1, arg2, ...)This function scans a string according to format and saves the result to the remaining parameters; format stringMay contain the following sections: • Spaces or tabs//ignored in processing • Normal characters (excluding%)///matching input stream next white character • Conversion instructions///:%, * (Assignment forbidden character, optional), value (Specify maximum field width, optional), h/l/l (Specify target object width, optional), convert characters;The general conversion result is stored in the variable that the corresponding parameter points to, but if there is * in the conversion description, the input field is skipped and no assignment is made; input field definition: A string that does not include a whitespace character, defined as the next whitespace character or the specified field width ; So scanf will read the input over the line boundary (because the newline character is also a blank character); whitespace characters include: space character , carriage return, line break, page break, Horizontal tab, Portrait tab;    Basic Conversion instructions for scanf (input data--"parameter type):   d: decimal integer------------------------int *; type • I: integer--------------------------------int * Type, can be octal (0 start) or hexadecimal (0x or 0X) · o: octal integers (can not start with 0)--"int type • U: unsigned decimal integer-----------------" unsigned * type • x: hexadecimal integer (0x or 0X similar to eight)---"int * type · C: Character-------------------------------char * Type, the subsequent multiple (default 1) input characters are stored in the specified position, usually do not skip the white space character, if you want to read into the next non-whitespace character can use%1s S: String (unquoted)---------------char * type, pointing to an array of characters that are sufficient to hold the string (including ' E,f,g '): floating-point number (may include sign, decimal, exponent)--"float * type%: Character%---------- -------------------"No assignment operationd,i,o,u,x can be added H (short) or L (long) before e,f,g, plus L (double);For example:Double V;while (scanf ("%lf", &v) ==1) ...For example, to read input lines in such a date format: DEC 1988int day, Year;char monthname[20];scanf ("%d%s%d", &day, MonthName, &year); The array name itself is the pointerThe character literal can also appear in the scanf format string, but it must match the same character in the input, for example, the following program can read the date data in the form such as Mm/dd/yy:int day, month, year;scanf ("%d/%d/%d", &day, &month, &year);scanf ignores spaces and tabs in the format string; it skips whitespace when reading input, and if you want to read an input that is not fixed (such as the date format may be any of the above), it is best to read one line at a time (such as the Getline function) and then use SSCANF to separate the appropriate format into the read; scanf can be mixed with other input functions; the next call always starts reading the data from the first character that is not read;Note that all of its parameters are pointers, and such errors are generally not checked by the compiler;7.5 File AccessThe standard input and output are automatically provided by the operating system to program Access;Example: Write a program to access the file, and the file it accesses is not connected to the program;Write Cat program: a batch of named files to output to the standard output; For those programs that cannot access the file by name, it can also be used as a generic input collector , such as the following command line:Cat x.c y.c//Print the contents of files x.c and y.c on standard outputHow do you associate the external name of the file that the user needs to use with the statement that reads the data? library function fopen. fopen uses an external name such as x.c to make some necessary connection and communication with the operating system (without concern for its details) and returns a "file pointer" that can then be used for file read and write operations;The file pointer points to a structure that contains information about the file, including the location of the buffer, the position of the current character in the buffer, the read or write state of the file, whether an error occurred, or whether the end of the file is reached, etc., without concern for these details, as <stdio.h> This structure file is defined in the program by simply declaring a pointer to it as follows:   FILE *FP;  file, like int, is a type name, not a struct tag, which defines a file *fopen (char *name, char *mode) through a typedef; Call: Fp=fopen (name, mode);The first parameter is a string, contains the file name , and the second parameter is the access pattern, which is also a string that specifies how the file is to be used (allowed modes: read ("R"), Write ("W"), Append ("a"), which distinguishes between text files and binary files in the system, which needs to add the character "B" in the string;write an existing file, the original content will be overwritten, append an existing file, the original content remains the same, write or append a nonexistent file, the file will be created (if possible), read the non-existent file will cause an error, other operations may also cause errors, such as reading a file without Read permission; , fopen will return null;after the file is opened, consider reading and writing, there are many ways, the simplest is:int getc (FILE *fp); Returns the next character in the input stream to which the file pointer fp is pointing, or returns eofint PUTC (int c, file *fp) to the end of the file; Writes the character C to the file that the FP points to, and returns the characters written, and an error returns EOFsimilar to GetChar and Putchar,getc and PUTC are also macros rather than functions;when starting a C program, the operating system is responsible for opening 3 files (standard input, standard output, standard error) and supplying their file pointers (stdin, stdout, stderr, declared in <stdio.h>) to the program In most environments, stdin points to the keyboard, stdout and stderr point to the display; stdin and stdout can be redirected to a file or pipeline;GetChar and Putchar can be defined as follows:#define GETCHAR () getc (stdin) #define PUTCHAR (c) PUTC ((c), stdout) formatted input and output of the file--FSCANF and Fprinf: The difference between scanf and printf is simply to add a file pointer before the format string parameter: int fscanf (file *fp, char *format, ...) int fprintf (FILE *fp, char *format, ...)The file pointers stdin and StdOut are constants of type *, and are not assignable;in your cat program:the FileCopy function can be realized through the loop of getc and PUTC;Loop read into argc and argv corresponding elements, open the corresponding file name, judgment and FileCopy;functionint flose (file *fp) performs and fopen the opposite operation, disconnecting the connection between the file pointer and the external name established by the fopen and releasing the file pointer for use by other files;It is a good programming habit to release a file pointer when it is no longer needed, and another reason to execute fclose on the output file: It writes the output from the buffer that the PUTC function is collecting to the file;If you do not need to use stdin and stdout, you can also close them off, you can also use the library function Freeopen to reassign them, when the program terminates normally, the program will automatically call the Fclose function for each open file;7.6 Error HandlingCat Program error handling function is not perfect: a connection for some reason can not open the file, the corresponding diagnostic information to be printed at the end of the output of the connection; output to the screen, this processing method is acceptable, if the output to another file or through the pipeline output to another program, it is unacceptable; Improved Method:   1) Assign another output stream stderr to the program in the same way as stdin and stdout, and even if STDOUT is redirected, the output written to stderr is usually displayed on the screen;2) using the standard library function exit, it terminates the execution of the calling program when it is called, and any process that invokes the program can get the parameter value of exit, so it can be tested by another program that uses the program as a child process to test the success of the program; (By convention, A return value of 0 indicates that everything is OK, not 0 indicates an exception occurred)exit calls the Fclose function for each opened output file to write all the output in the buffer to the appropriate file;in Main program main, statement return expr is equivalent to exit (expr), but using exit has one advantage:?? It can be called from other functions, and can be found in a pattern lookup program similar to that described in chapter 5th;int ferror (FILE *fp)//If an error occurs in the stream FP, the function returns a non-0 valuein this example, the function is used to check for errors in the flow stdout, although output errors are rare, but also exist (such as when the disk is full), so mature product programs should check for this type of error;int feof (file *FP)///similar to ferror, this function returns a non-0 value when the specified file reaches the end of the filefor any important program, the program should return meaningful and useful values;7.7 lines of input and line outputThe Standard library provides an input functionsimilar to getline fgets:Char *fgets (char *line, int maxline, FILE *FP) The function reads the next input row (including the newline character) from the stream FP and stores it (ending with '% ') in the character array line, up to a maximum of maxline-1 characters Normally, Fgets returns line, and returns null if the end of the file or an error occurs; (Getline is the length of the returned row)output function fputs:int fputs (char *line, FILE *FP) This function writes a string (without a newline character) to the stream FP; An error returns EOF, otherwise a non-negative value is returned (this differs from ferror);Library functions The function of get and puts is similar to fgets and fputs, but they operate on stdin and stdout; but gets and puts delete or add a newline character at the end when reading or writing a string;7.8 Other functionsdescribes some of the functions that are particularly useful in standard libraries, with details and other functions in appendix B; string manipulation functions , available in header file <string.h> (s,t is char * type, c,n int type):   strcat (s,t);//After a connection to the previous end of Strncat (s, t, n);//After a first n words connect prompt to the previous end strcmp (S, t);//Returns a negative integer, 0 or positive integer strncmp (s, t, N) based on the comparison;// Compare the first n strcpy (s, t);//Copy the latter to the previous position strncpy (s, t);//After a first n characters are copied to the previous position strlen (s);//return string length STRCHR (s, c);//Find the latter in the previous string , returns the pointer to the first occurrence of the position or EOFSTRRCHR (S, c);//finds the latter in the previous string, returns a pointer to the last occurrence of the position, or EOF character category test and conversion functions (defined in header file <ctype.h>):   Isalpha (c);//The letter returns non-0isupper (c);//Uppercase returns non-0islower (c);//lowercase returns non-0isdigit (c);//The number returns non-0isalnum (c);// is a letter or number returned non-0isspace (c);//is a blank character return non-0toupper (c);//returns the uppercase form of C ToLower (c);//returns the lowercase form of c ungetc function (provided by standard library, more limited in function compared to self-compiled ungetch):   int ungetc (int c, file *FP) This function writes the character C back to the stream FP, or, if successful, returns the EOF; each file can receive only one character, and unget can be used with any input function, such as scanf, getc, GetChar; command execution function :   the function system (char*) executes the command contained in the string s. Then continue to execute the current program; s content is largely related to the operating system used; The following is a small example of Unix:System ("date"); The execution program date, which prints the date and time of the day on the standard output, and returns an integer state value (from the executed command, which is related to the system, such as the return value of exit returned under Unix) Storage Management functions :   function malloc and calloc for dynamically allocating storage blocksvoid *malloc (size_t N) is allocated successfully when the function returns a pointer to an uninitialized storage space of n-byte length; otherwise returns null; void *calloc (size_t n, size_t size) A successful allocation returns a pointer to the free space, which is initialized to 0 to accommodate an array of n specified lengths of objects; otherwise null is returned;depending on the requested object type, the pointers returned by malloc and Calloc meet the correct alignment requirements, and the following example makes type conversions:int *ip;ip= (int *) calloc (n, sizeof (int));free (p) frees the storage space that P points to, where p is the pointer to the call to malloc or calloc; there is no limit to the order of storage space release, but it would be a fatal error if you release a space pointed to by a pointer not called malloc or calloc; the storage blocks allocated by malloc can be released in any order; Mathematical Functions (<math.h> declared more than 20):each function has 1 or 2 arguments of type double and returns a double type;Sin (x)//x with Radian cos (x) atan2 (y, x)//y/x's Arc tangent exp (x) log (x)//Natural logarithm log10 (x) Pow (x, y)//calculation x^ysqrt (x) fabs (x) random number generator functionThe function rand () generates a sequence of pseudo-random integers between 0 and Rand_max (symbolic constants, defined in <stdlib.h>), and the following methods can generate random floating-point numbers between 0 and 1: #define Frand () ((double) rand ()/ (rand_max+1.0))If a function that generates a random floating-point number is already available in the library used, it may have better statistical characteristics than the above function.The function srand (unsigned) sets the number of seeds of Rand, and the portable implementations of Rand and srand that follow the standard are given in section 2.7 .

C Programming Language (2nd edition • New version) Chapter 7th input and output

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.