Read the C programming language (9)

Source: Internet
Author: User

Chapter 7 describes the database functions related to input and output. When talking about library functions, the author said, "programs that confine their system interactions to facilities provided by the standard library can be moved from one system to another without change. "It can be seen that the standard library function should be used wherever possible in the program and the operating system, which can increase portability.

Section 1 Standard Input and Output

This section describes the model of standard input and output, which is to think of the input and output content as a compaction stream. This sort of stream consists of a line of characters, each line ends with '/N. In addition, the author also introduced the redirection and pipe mechanisms, which should be familiar to anyone who has used dos and Unix/Linux.

Finally, the author mentioned an interesting thing: library functions such as getchar, putchar, and tolower are macros, which can avoid the overhead of function calls. How to implement it is necessary to wait until Chapter 8 introduces it.

Section 2 formatting output-printf

This section describes printf and sprintf in detail. If you need to strictly format the output for writing programs later, refer to this section. At last, the author gave us a wake-up question:

Printf (s);/* fails if S contains % */
Printf ("% s", S);/* safe */

Generally, the former is used to output a string, but if the string contains %, it will fail. The latter is the safe method.

Section 3 variable length parameter list

This section describes how to implement a function with a variable number of parameters such as printf. It focuses on the function declaration and how to obtain unnamed parameters. First, let's see how such a function is declared:

Int printf (char * FMT ,...)

The ellipsis (...) indicates that the number and type of parameters are variable. It can only be used at the end of the parameter list.

To obtain an unnamed parameter, you must first include the header file <stdarg. h>. The va_list, va_start, va_arg, and va_end files defined in this header file can be used together to complete this task. For more information, see the example given by the author:

# Include <stdarg. h>
/* Minprintf: Minimal printf with variable argument list */
Void minprintf (char * FMT ,...)
{
Va_list AP;/* points to each unnamed ARG in turn */
Char * P, * sval;
Int ival;
Double dval;
Va_start (AP, FMT);/* Make AP point to 1st unnamed Arg */
For (P = FMT; * P; P ++ ){
If (* P! = '% '){
Putchar (* P );
Continue;
}
Switch (* ++ p ){
Case 'D ':
Ival = va_arg (AP, INT );
Printf ("% d", ival );
Break;
Case 'F ':
Dval = va_arg (AP, double );
Printf ("% F", dval );
Break;
Case's ':
For (sval = va_arg (AP, char *); * sval; sval ++)
Putchar (* sval );
Break;
Default:
Putchar (* P );
Break;
}
}
Va_end (AP);/* clean up when done */
}

Section 4 format input-scanf

This section describes the counterpart of printf and sprintf: scanf and sscanf. Sscanf accepts input from a specified string. These two functions are similar in nature, except that one is an output function and the other is an input function. In addition, the input parameters in scanf and sscanf must be pointers.

Generally, we use scanf to read only one value. In fact, we can also read multiple values. For example, if you want to read information such as 25 Dec 1988 from the input stream, you can write the following statement:

Int day, year;
Char monthname [20];
Scanf ("% d % S % d", & day, monthname, & year );

Read the information of year, month, and day at a time. In addition, if the read format is not fixed, you can read a row at a time, and then use sscanf to match the desired format from this line of information.

Section 5 File Access

This section describes the library functions and related usage for file access, including fopen, fclose, GETC, and putc. GETC and putc are similar to getchar and putchar, except that the former is used for file read and write while the latter is used for standard input and output. Their relationship can be seen from the following two forms:

# Define getchar () GETC (stdin)
# Define putchar (c) putc (c), stdout)

This is exactly the implementation of getchar and putchar. Stdin and stdout are two file pointers maintained by the system, and a similar file pointer is stderr. Generally, stdin is connected to the keyboard, while stdout and stderr are connected to the monitor.

To format input and output, the author also introduces two functions similar to scanf and printf:

Int fscanf (File * FP, char * format ,...)
Int fprintf (File * FP, char * format ,...)

The difference is that they only specify the file input and output, and the first parameter specifies the file pointer.

Section 6 error handling-stderr and exit

The content of this section is very valuable, especially when you are doing a serious project. When I was studying C language in the college age, I did not take the test in this aspect, so it has always been a weak link for me. This time I read a book to find out a lot of confused things.

Previously, I knew that stdout and stderr are both output to the monitor, but I don't know what practical differences they have except for concept. The author tells us the difference here: Output written to stdout may be redirected (another file or pipeline), even if an error occurs during processing, the error message is redirected, and the output written to stderr is displayed on the screen even if the standard output is redirected.

I don't know the difference between exit and return. After reading the author's explanation, I understand that in a program, as long as exit is called, the program immediately stops execution, while return is only a function return. Therefore, in the main function, exit and return are equivalent, but they are completely different in other functions. The advantage of exit is that no matter who calls it, the program execution is exited as long as it is called.

Section 7 Input and Output

This section describes two row input/output library functions for files: fgets and fputs. They are similar to library functions gets and puts, except that the latter reads and writes data on stdin and stdout. This section is not worth a lot of attention, but it can be seen from the fact that many standard input/output functions have corresponding file manipulation functions, in fact, standard input and output functions are only special cases of file input and output functions-they operate on two special file pointers stdin and stdout.

Section 8 Other Functions

This section lists many useful library functions and can be used as a good reference. The following lists some important points:

  • Int ungetc (int c, file * FP): When you accidentally read one more character from the file, it doesn't matter. Use this function to return it. In fact, in most cases, multiple reads are intentional, and the program needs to, but remember that a file can only return one character.
  • System (char * s): calling this function will allow the system to execute the commands in the string. What can be a command is closely related to a specific operating system.
  • Malloc and calloc: I saw the difference between the two functions on the Forum a few days ago. I think the only obvious difference is that calloc initializes the applied memory to 0. As for its usage, it is a matter of benevolence. I feel that calloc is more suitable for allocating space to arrays from the parameters it accepts, while malloc is a wildcard and can be adapted to a wider area.
  • Rand () generates a random integer between 0 and rand_max, and srand (unsigned) sets seed for it ). To generate a random floating point number between 0 and 1, you can define it as follows: # define frand () (double) rand ()/(rand_max + 1.0 ))
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.