C Primer Plus (13)

Source: Internet
Author: User

13.1 communicate with files

One way for programs to communicate with files is file redirection.

13.1.1 what is a file?

A file is usually a named storage area on the disk.
C regards the file as a continuous byte sequence, and each byte can be read separately.
Ansi c provides two file views: Text View and binary view.

13.1.2 Text View and binary View

In the binary view, each byte in the file can be accessed by the program. In the text view, the content displayed by the program may be different from the content of the file.
For example, when reading a file using the text view, the local environment representation at the end of the line is mapped to the C view. Similarly, during output, the end of a row in view C is mapped to a local environment notation.

13.1.3 I/O Level

In addition to the file view, you can select two I/O levels in most cases.
Low-level I/O uses the Basic I/O services provided by the operating system, and standard-Level I/O uses a standard C library function package and the definition in the stdio. h header file.
Ansi c only supports standard I/O packages because it cannot guarantee that all operating systems can be expressed using the same low-level I/O model.

13.1.4 standard document

C program automatically opens three files for you. Standard input, standard output, and standard error output.

Standard I/O 13.2

In addition to portability, standard I/O packages have two advantages over low-level I/O packages.
First, the standard I/O package contains many dedicated functions, which can easily handle different I/O problems.
Second, the input and output are buffered. This buffer greatly improves the data transmission rate.

13.2.1 check command line parameters

First, check the value of argc to see if there are command line parameters. The string argv [0] is the name of the program.
The exit () function closes all open files and terminates the program. The General Convention is that the transfer value of a normally terminated program is 0, and that of an abnormally terminated program is not 0. You can also use exit (EXIT_SUCCESS) and xit (EXIT_FAILURE ).
According to ansi c, using return in the originally called main () has the same effect as calling exit. // Note that it is "initially called". If main () is in a recursive program, exit () will still terminate the program. However, return transfers control to the first level of recursion until the beginning.

13.2.2 fopen () function

The program uses fopen () to open a file. Its first parameter is the name of the file to be opened, or the address of the string containing the file name. The second parameter is a string used to specify the file opening mode.
If the file cannot be opened, the fopen () function returns a null pointer.

13.2.3 getc () and putc () Functions

For example, ch = getc (fp), putc (ch, fpout );
Putc (ch, stdout); the second parameter is the file pointer related to the standard output, so the effect is the same as that of putchar (ch.

13.2.4 end of File

Therefore, you can add a condition while (ch = fgetc (fp ))! = NULL.

13.2.5 fclose () function

13.2.6 standard file pointer

13.3 file I/O: fprintf (), fscanf (), fgets (), and fputs () Functions

13.3.1 fprintf () and fscanf () Functions

The rewind () command returns the program to the beginning of the file, so that the last while loop can print the file content.

13.3.2 fgets () and fputs () Functions

The fgets () function accepts three parameters. The first parameter is used to store the input address. The second parameter is an integer, indicating the maximum length of the input string. The last parameter is a file pointer pointing to the file to be read.
Fgets (buf, MAX, fp) This function reads the back of the first line break it encounters, or reads a character less than the maximum length of the string, or reads to the end of the file. Then, the fgets () function adds an empty character to the end to form a string.
Therefore, the maximum length of a string represents the maximum number of characters plus an empty character.
The fputs () function accepts two parameters. Each of them is a string address and a file pointer, and the string is written to the specified file. Fputs (but, fp );

13.3.3 gets () andFgets() Function

13.4 Random Access: fseek () and ftell () Functions

The fseek () function allows you to treat a file as an array, and directly move the file opened in fopen () to any byte. It accepts three parameters and returns an int value. The ftell () function returns the current position of a file with a long value.
In the three parameters of fseek (),
The first parameter is a FILE pointer to the FILE to be searched. You must have used fopen () to open the file.
The second parameter is called offset, indicating the distance from the start point to move. This parameter must be a lon value, which can be positive (forward), negative (backward), or zero (not moving ).
The third parameter is the mode used to identify the start point. SEEK_SET: file start SEEK_CUR: file current SEEK_END: file end
Example: fseek (fp, 0L, SEEK_SET );
If everything is normal, fseek () returns 0. -1 is returned if an error occurs.
The ftell () function is of the long type and returns the current position of the object. The ftell () function determines the file location by returning the number of bytes from the start of the file. The distance from the first byte of the file to the start of the file is byte 0, and so on.
Last = ftell (fp); the number of bytes from the beginning to the end of the file is assigned to last.

13.5 standard I/O insider

The first step to use standard I/O is to open a file with fopen. The fopen () function not only opens a file, but also creates a buffer and a data structure that contains file and buffer-related data.
The next step is to call an input function declared in the stdio. h header file, such as fscanf. A piece of data is copied from the file to the buffer.
The output function writes data to the buffer. When the buffer is full, the data is copied to the file.

13.6 other standard I/O functions

13.6.1 int ungetc (int c, FILE * fp) Function

This function puts the character specified by c back into the input stream. If a character is placed in the input stream, the next time the standard input function is called, the character will be read.
For example, ch = getchar (); ungetc (ch, stdin );

13.6.2 int fflush () function

The function prototype is int fflush (FILE * fp). It can send any unwritten data in the buffer to an output FILE specified by fp. This process is called a refresh buffer. If fp is a null pointer, all output buffers will be refreshed.

13.6.3 int setvbuf () function

The function prototype is int setvbuf (FILE * restrict fp, char * restrict buf, int mode, size_t size );
The setvbuf () function creates a replacement buffer for standard I/O functions. After opening the file, you can call this function before performing any operations on the stream. The fp specifies the stream, and the buf points to the used buffer zone. If buf is NULL, the buffer is automatically allocated.
The size variable is the size of the array specified by the setvbuf () function.
Mode is selected from the following options:
_ IOFBF indicates full buffering, _ IOLBF indicates row buffering, and _ IONBF indicates no buffering. If execution is successful, the function returns a zero value. Otherwise, a non-zero value is returned.

13.6.4 binary I/O: fread () and fwrite () Functions

If the data is stored in a file that uses the same representation method as the program, the data is stored in binary format. This binary service is provided for standard I/0, fread (), and fwrite () functions.
In fact, all data is stored in binary format. If all the data in the file is interpreted as character encoding, we say that the file contains text data. If part or all of the data is interpreted as binary, the file contains binary data.
Char buffer [256]; fwrite (buffer, 256, fp); the third parameter indicates the number of data blocks. This call writes a-byte data block from the buffer to the file.
Double earning [10]; fwrite (earnings, sizeof (double), 10, fp); write the data in the array into a file and divide the data into 10 pieces, each of which is double in size.
Fread (earnings, sizeof (double), 10, fp); restores the array in the previous example and returns the number of successfully read projects.

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.