C -- file read/write

Source: Internet
Author: User
Tags rewind


Chapter 4 Documents

Learning requirements:

1. understand the concept of a file
2. Measure the test taker's knowledge about how to open and close a file.
3. Measure the test taker's knowledge about file read/write, locating, and error detection methods.

Content:

C file Overview

1. "file": "file" refers to an ordered set of related data. Data is stored in external media (generally disks, tapes, and CDs) as files, and managed in the operating system as files. Use a file name as the identifier of the access file.

2. The C language regards a file as a byte sequence, which is composed of a series of bytes. According to the data organization form in the file, the data file can be divided into ASCII code files and binary files.

An ASCII code file, also known as a text file, stores an ascii code in each byte.

Binary File: stores data in the memory in the disk as a memory.

For example, a decimal integer of 10000 occupies two bytes in the memory. The storage format is: 00100111,00010000. This method is also used to store binary files.

However, in an ASCII file, the decimal integer 10000 is stored in 31 H, 30 h, 30 h, 30 h, or 30 h, which occupies five bytes, they are ASCII codes of 1, 0, 0, 0, 0, and 0 letters.

3. According to the operating system's read/write Method for Disk Files, files can be divided into two types: "buffer File System" and "non-buffer File System ".

Buffer File System: the operating system opens a read/write buffer for every file in use in the memory. The data output from memory to the disk must be sent to the buffer in the memory before being sent to the disk after the buffer is full. If data is read from the disk to the memory, a batch of data is input from the disk file to the memory buffer, and then data is sent to the program data zone one by one from the buffer zone.

 

Non-buffer File System: the operating system does not automatically open a fixed size read/write buffer, and the Program sets a buffer for each file.

In Unix systems, a buffer file system is used to process text files, while a non-buffer file system is used to process binary files. The ansi c standard only uses a buffer file system.

In the C language, there are no input/output statements, and database functions are used to read and write files. This chapter only describes the buffer file systems specified by ansi c.

File Type pointer

In the buffer file system, each file used opens a "file information area" in the memory ", used to store information about a file (such as the file name, current file read/write location, and file operation method ). This information is stored in a struct variable, which is defined by the system and named file. The following file types are declared in the stdio. h file of Turbo C 3.0:

 

Typedef struct {
Int level;/* the degree to which the buffer is "full" or "empty */
Unsigned flags;/* File status flag */
Char FD;/* file descriptor */
Unsigned char hold;/* do not read characters without a buffer */
Int bsize;/* buffer size */
Unsigned char * buffer;/* Data Buffer location */
Unsigned char * CURP;/* pointer, current point */
Unsigned istemp;/* temporary file, indicator */
Short token;/* used for validity check */
} File;

The general format of defining file pointer variables is:

File * file structure pointer variable name

Example: file * FP;

Note: The corresponding file can be called only through the file pointer.

Open File (fopen function)

File Operation Process: The operation on the disk file must be "open first, read/write, and finally close ".

Description of "open" file: searches for the specified file or creates a new file from the disk in a certain way.

Ansi c specifies the standard input/output function library and uses the fopen () function to open a file. The fopen () function is called in the following ways:

File * FP;

Fp = fopen (file name, file method );

 

For example:

File * FP;

Aaaafp = fopen ("file1", "R ");

Indicates that the file named file1 is to be opened and the file type is "read". If the file is opened successfully, a pointer to file1 is returned. If the file fails to be opened, a null pointer is returned.

The following table describes how to use files:

File Usage

Description

"R" (read-only) Open a text file for the input
"W" (write only) Open a text file for the output
"A" (append) Open a text file for append
"Rb" (read-only) Open a binary file for the input
"WB" (write only) Open a binary file for the output
"AB" (append) Open a binary file for append
"R +" (read/write) Open a text file for read/write
"W +" (read/write) Create a text file for read/write
"A +" (read/write) Open a text file for read/write
"RB +" (read/write) Open a binary file for read/write
"WB +" (read/write) Create a binary file for read/write
"AB +" (read/write) Open a binary file for read/write

 

Note:

1. A file opened in the "r" mode can only be used to input data to a computer, but cannot be used to output data to the file, and the file should already exist, you cannot use the "r" method to open a non-existing file (that is, the input file). Otherwise, an error occurs.

2. A file opened in the "w" mode can only be used to write data to the file (that is, the output file), but cannot be used to input data to the computer. If the file does not exist, create a new file when it is opened. If the file exists, delete the file and create a new file.

3. If you want to add new data to the end of the file (do not delete the original data), you should use the "A" method to open it. However, the file must exist at this time; otherwise, an error occurs.

4. files opened in the "R +", "W +", and "A +" modes can be used to input or output data.

5. If the file cannot be opened, the fopen () function will return an error message. If the file does not exist, a null pointer is returned.

Open a file in the following ways:

File * FP;

If (FP = fopen ("file1", "R") = NULL)

{
Printf ("cannot open this file \ n ");

Exit (0 );

}

That is, if there is an error, the terminal outputs "cannot open this file ". The exit () function is used to close all files and terminate ongoing programs.

6. When entering a text file into a computer, convert the carriage return linefeed into a line break. In the output, convert the line break to the carriage return and line feed characters. Binary files are not converted.

 

Close the file (fclose function)

After using a file, you should close it. The "close" file means that the file pointer is detached from the file. Then, you cannot use this pointer to read or write the file associated with it. The habit of closing all files before the program is terminated should be developed.

Use the fclose function to close the file. The fclose function is generally called in the following format:

Fclose (File pointer)

For example:

Fclose (FP );

The fclose function also returns a returned value. When the file is closed successfully, 0 is returned; otherwise, EOF (-1) is returned ).

File read/write

After the file is opened, you can read and write it. Common read/write functions are described as follows.

1. fputc and fgetc functions (putc and GETC functions)

(1) fputc Function

Write characters to a disk file. The general calling method is as follows:

Fputc (CH, FP)

Write the character (CH value) into the file pointed to by FP. Return the ASCII code of the CH character when the request succeeds, and return the ASCII code when the request fails.

EOF (in stdio. H, the value of the symbol constant EOF is equal to-1 ).

 

(2) fgetc () function

Reads a character from a specified file. The fgetc function is called in the following form:

Ch = fgetc (FP );

Read a character from the file pointed to by FP and return the read character to the variable ch. In case of a text file, the end mark EOF the file is returned at the end of the file. For binary files, use feof (FP) to determine whether the end of the file is met, and feof (FP) = 1 indicates that the end of the file is met.

Read the file content from a text file in sequence and display it on the screen. You can use:

Ch = fgetc (FP );

While (Ch! = EOF)

{
Putchar (CH );

Ch = fgetc (FP );
}

Read the file content in sequence from a binary file. You can use:

While (! Feof (FP ))
{
Ch = fgetc (FP );
....
}

This method also applies to text files.

 

(3) fputc function and fgetc Function Application Example

In Example 13_1, enter some characters on the keyboard and send them to disk files one by one until # is input on the keyboard.

Example 13_2 copies the content of a disk file to another disk file.

Fread and fwrite Functions

Fread and fwrite functions are used to read and write a data block. They are generally called in the following ways:

Fread (buffer, size, Count, FP );

Fwrite (buffer, size, Count, FP );

Where:

Buffer: a pointer. For fread, It is the storage address for reading data. For fwrite, It is the address of the data to be output.

Size: the number of bytes to read and write.

Count: the number of size-byte data items to be read and written.

FP: file pointer.

If a file is opened in binary format, fread and fwrite functions can be used to read and write any type of information, for example:

Fread (F, 4, 2, FP );

F is a real-type array name. A real variable occupies 4 bytes. This function reads two 4-byte data from the file pointed to by FP and stores it in array F.

 

If the following struct types exist:

Struct student_type
{
Char name [10];

Int num;

Int age;

Char ADDR [30];

} STU [40];

The struct array Stu has 40 elements, each of which is used to store the data of one student. Assume that the student data has been stored in the disk file. You can use the following for statement and fread function to read the data of 40 students:

For (I = 0; I <40; I ++)

Fread (& STU [I], sizeof (struct student_type), 1, FP );

Or:

Fread (& STU [I], sizeof (struct student_type), 40, FP );

 

Similarly, the following program can output the student data in the memory to the disk file:

For (I = 0; I <40; I ++)/* write a student each time */

Fwrite (& STU [I], sizeof (struct student_type), 1, FP );

Or write only once

Fwrite (STU, sizeof (struct student_type), 40, FP );

Example 13_3 input a batch of student data on the keyboard and store the data on the disk.

Fprintf and fscanf Functions

The fprintf and fscanf functions are similar to those of printf and scanf. They are all formatted read/write functions. The read and write objects of fprintf and fscanf functions are disk files, while those of printf and scanf functions are terminals.

They are generally called in the following format:

Fprintf (File pointer, Format String, output list );

Fscanf (File pointer, Format String, input list );

In addition to adding a "file Pointer", the usage is the same as that of printf ()/scanf.

For example:

Fprintf (FP, "% d, % 6.2f", I, T );

It outputs the values of integer variables I and real variables T to the file pointed to by FP in the format of % d and % 6.2f. If I = 3, T = 4.5, the following string is output to the disk file:

3, 4.50

 

Similarly, the fscanf function can be used to read ASCII characters from disk files:

Fscanf (FP, "% d, % F", & I, & T );

If the disk file contains the following characters: 3, 4.5, send the data of the disk file 3 to variable I, and 4.5 to variable t.

The fprintf and fscanf functions are used to operate disk files. Since the ASCII code must be converted to the binary format during input, the binary code must be converted to a character during output, which takes a lot of time. Therefore, when the memory and disk frequently exchange data, it is best to use fread and fwrite functions instead of fprintf and fscanf functions.

Other read/write Functions

1. putw and getw Functions

The putw and getw functions are used to read and write a single word (integer) to a disk file ). For example:

Putw (10, FP);/* integer 10 Write File FP */

I = getw (FP);/* read an integer from the file FP to the variable I */

2. fgets and fputs Functions

The fgets function reads a string from a specified file. For example:

Fgets (STR, N, FP)/* reads n-1 bytes from the file FP to STR, and adds '\ 0' to the last byte of Str '*/

The fputs function outputs a string to a specified file. For example:

Fputs (STR, FP)/* write string STR into FP */

 

File Location

The file has a location pointer pointing to the current read/write location. After each read/write operation, the pointer automatically points to the next character. You can use the ftell () function to obtain the current position pointer, or use the rewind ()/fseek () function to change the position pointer so that it points to the position to be read/written.

1. Rewind Function

The general format is rewind (FP). function: point the position pointer of the file FP to the file.

In Example 13_4, the content of a file is displayed on the screen and copied to another file.

2. fseek function and random read/write

Stream files can be read and written in sequence or randomly. The key is to control the position pointer of files.

You can use the fseek function to change the position pointer of a file. The fseek function is called in the following format:

Fssek (file type pointer, displacement, starting point );

Function: starts the file position pointer from the start point and moves the specified number of bytes of the displacement. 0 is returned for success, and 0 is returned for failure.

Start Point Symbol constant Value
File start location Seek_set 0
Current location Seek_cur 1
End of File Seek_end 2

Example 13_5 contains 10 students (0 ~ 9), read the data of students 1, 3, 5, 7, and 9, and display it on the screen.

 

3. ftell Functions

The ftell function is used to obtain the current position in the stream file, which is expressed by the displacement relative to the beginning of the file. If it fails, the returned value is-1l.

For example:

I = ftell (FP );

If (I =-1l) printf ("error \ n ");

Variable I stores the current location. If an error occurs when calling a function (if the FP file does not exist), an error is output ".

Error Detection

The C standard provides functions to check for errors in input/output function calls.

1. ferror Function

In file operations, if an error occurs, in addition to the response of the return value of the operation function (for example, the fopen () function returns NULL), you can also use the ferror function to determine whether an error occurs. It is generally called in the following form:

Ferror (FP)

Function: If no error occurs in the last file operation, 0 is returned; otherwise, non-0 is returned.

2. clearerr Functions

The clearerr function sets the file error mark and end mark to 0. After an error occurs in the file operation, the value of the ferror (FP) function is a non-0 value, which will be retained in the system. After the clearerr (FP) function is called, the value of the ferror (FP) function is 0.

Summary of file input and output

Common buffer file system functions

Category Function Name Function
Open a file

Fopen ()

Open the file.
Close file Fclose () Close the file.
File Location

Fseek ()

Rewind ()

Ftell ()

Change File Location pointer location

Place the file location pointer at the beginning of the file

Returns the current value of the file position pointer.

File read/write

Fgetc (), GETC ()

Fputc (), putc ()

Fgets ()

Fputs ()

Getw ()

Putw ()

Fread ()

Fwrite ()

Fscanf ()

Fprintf ()

Obtains a character from a specified file.

Output characters to a specified file.

Reads a string from a specified file.

Output the string to the specified file.

Reads a word (INT type) from a specified file ).

Output a word (INT type) to the specified file.

Reads data items from a specified file.

Write data items to a specified file.

Input data from a specified file in the format.

Write data to a specified file in the specified format.

File status

Feof ()

Ferror ()

Clearerr ()

If the end of the file is reached, the function value is "true" (not 0 ).

If an error occurs in file operations, the function value is "true" (not 0 ).

Set the value of the ferror and feof functions to zero.

 

 

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.