Document C operations

Source: Internet
Author: User
Tags rewind

Section 10. 1 C Overview

File is an important concept in programming. A file is a collection of data stored on an external media. A batch of data is stored in external media (such as disks) as files. The operating system manages data in files. That is to say, if you want to find data that exists in an external media, you must first find the specified file by file name, then read data from the file. To store data on external media, you must first create a file (identified by a file name) to output data to it.

§ 10. 2 file type pointer

In a buffer file system, the key concept is "file Pointer ". Each used file opens a region in the memory to store information about the file (such as the file name, File status, and current file location ). This information is stored in a struct type variable. The struct type is defined by the system and is named file. Some C versions have the following types of definitions in stdio. H files:

Typedef struct

{

INT-FD;/* file number */

INT-cleft;/* remaining characters in the buffer */

INT-mode;/* file operation mode */

Char *-nextc;/* location of the next character */

Char *-Buff;/* File Buffer location */

} File;

With the file type, you can use it to define several file-type variables to store the information of several files. For example, you can define an array of the following file type.

File-efile [-maxfile];

Defines a struct array-efile [], which has-maxfile elements.-maxfile is a symbolic constant, and its value is the maximum number of available files.

You can define pointer variables of the file type. For example:

File * FP;

FP is a pointer variable pointing to a structure of the file type. The FP can point to the struct variable of a file, so that the file information in the struct can be used to access the file.

 

§ 10. 3 open and close a file

And other advanced languages, you should "open" the file before reading and writing the file, and "close" the file after use.

10.3.1 file opening (fopen function)

Ansi c specifies the standard input/output function library, which uses the fopen () function to open files. The fopen () function is usually called in the following way:

FILE * fp;

Fp = fopen (file name, using the file method );

For example:

Fp = ("d: \ aa.txt", "r ");

It indicates that you want to open the aa.txt file in the ddisk root directory to read data. Upload File. It can be seen that when opening a file, the following information is notified to the compilation system: 1. The file name to be opened, that is, the name of the file to be accessed. 2. Use the file method (read or write ). 3. Specify which pointer variable to point to the opened file.

See Table 10.1 for how to use files.

Table 10.1

 

File Usage

Meaning

"R" (read-only)

Open a text file for the input

"W" (write only)

Open a text file for the output

"A" (append)

Add data to the end of a text file

"Rb" (read-only)

Open a binary file for the input

"WB" (write only)

Open a binary file for the output

"AB" (append)

Add data to the end of the binary file

"R +" (read/write)

Open a text file for read/write

"W +" (read/write)

Create a new 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 new binary file for read/write

"AB +" (read/write)

Open a binary file for read/write

 

Note:

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

2. files opened in "w" mode can only be used to write data to the file, but not to input data to the computer. If a file does not exist, a new file named after the specified name will be created when it is opened. If a file name already exists, delete the file and create a new file when it is opened.

3. If you want to add new data to the end of the file, open it in "a" mode, but the file must exist at this time. Otherwise, an error occurs. When opening, the position pointer is moved to the end of the file.

4. The file already exists when "r +" is used to input data to the computer. Use the "w +" method to create a file. First, write data to the file, and then you can read the data in the file.

5. If the "open" task cannot be implemented, the fopen function will bring back an error message. In this case, the fopen function will bring back a NULL pointer value. The following methods are commonly used to open a file:

If (fp = fopen ("file1", "r") = NULL)

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

Exit (0 );

} Check whether there is an error first. If there is an error, output "cannot open this file" on the terminal ". The exit function is used to close all files and terminate the calling process. Wait for the programmer to check the error and run it after modification.

6. You can use the preceding methods to open text files or binary files, and use the same buffer file system to process text files and binary files.

7. When a text file is input to 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. This type of conversion is not performed when binary files are used.

8. When the program starts running, the system automatically opens three standard files: standard input, standard output, and standard error output. These three files are usually associated with the terminal. The system automatically defines three file pointers, stdin, stdout, and stderr, pointing to terminal input, terminal output, and standard error output respectively. If the Program specifies to input data from the file referred to by stdin, it means to input data from the terminal keyboard.

Close the file 10.3.1 (fclose function)

Close a file to prevent misuse. "Close" means that the file pointer variable does not point to the file and cannot be used to read or write the file connected to it later, unless it is opened again, point the pointer variable to the file again.

Use the fclose function to close the file. The fclose function is generally called in the form of fclose (File pointer );

For example, fclose (fp); when the fclose function is used to open the file, the pointer is assigned to fp, and the file is closed. The habit of closing all files used before program termination should be developed. If the file is not closed, data will be lost. The fclose function returns a value. If the value is not 0, the return value is 0. If the value is not 0, an error occurs when the function is disabled.

 

§ 10. 4 file read/write

10.4.1 fputc and fgetc Functions

1. The fputc function writes a character to a disk file. The format is fputc (ch, fp );

Ch is the character to be output. It can be a character constant or a character variable. Fp is a file pointer variable, which gets the return value from the fopen function. The fputc function outputs the character (ch value) to the file pointed to by the fp. If the output is successful, the returned value of the fputc function is the output character. If the output fails, an EOF is returned.

Ii. fgetc Function

Read a character from a specified file. The file must be opened in read or read/write mode. The fgetc function is called in the following form:

Ch = fgetc (fp );

Fp is a file pointer variable, and ch is a character variable. The fgetc function returns a character to ch. If you encounter a file terminator when executing the fgetc read character, the function returns a file ending mark (EOF. If you want to read characters from a disk file sequentially and display them on the screen, you can:

Ch = fgetc (fp );

While (ch! = EOF)

{

Putcher (ch );

Ch = fgetc (fp );

}

Note: EOF is not an output character and cannot be displayed on the screen. If you want to read data from a binary file in sequence, you can use: while (! Feof (fp ))

{C = fgetc (fp );

Bytes

} When the file is not ended, the feof (fp) value is 0 .! The value of feof (fp) is 1. This method is also applicable to text files.

Iii. Examples of fputc and fgetc Functions

For example, enter some characters on the keyboard and send them to the keyboard one by one until you enter.

# Include <stdio. h>

Void main (void)

{FILE * fp;

Char ch, filename [10];

Scanf ("% s", filename );

If (fp = fopen (filename, "w") = NULL)

{

Printf ("cannot open file \ n ");
Exit (0 );

}

Ch = getchar ();
While (ch! = '#')

{

Fputc (ch, fp );

Putchar (ch );

Ch = getchar ();

}

Fclose (fp );

}

Run as follows: file1.c (enter the disk file name)

Computer and c # (enter a string)

Computer and c (enter a string)

In this example, enter the disk file name "file1.c" from the keyboard, enter the character "computer and c" to write the disk file, and display these characters on the screen.

12.4.2 fread and fwrite Functions

The getc and putc functions can be used to read and write a character in a file. But it is often required to read a group of data at a time. fread and fwrite functions can be used to read and write a data block. They are generally called in the following form:

Fread (buffer, size, count, fp );

Fwrite (buffer, size, count, fp );

Buffer: a pointer. Fread is the storage address for reading data. Fwrite is the address of the output data.

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 the file is opened in binary format, fread and fwrite functions can be used to read and write any type of information, such as fread (f, 4, 2, fp). f is a real-type array name. A real variable occupies 4 bytes. This function reads data twice from the file pointed to by fp and stores it in array f. If the following struct type is used:

Sturt student_type

{Char name [10];

Int num;

Int age;

Char addr [30];

} Stud [40]; The stud array contains a total of 40 elements. Each element is used to store one student data. Assume that the student data is already stored in a disk file, you can use the following statement to read 40 student data.

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

Fread (& stud [I], sizeof (struct student_type), 1, fp );

Similarly, the following statements can output data of Middle School Students in memory to disk files.

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

Fread (& stud [I], sizeof (struct student_type), 1, fp );

The following is a complete program.

For example, input the data of four students on the keyboard and then store them in a disk file.

# Include <stdio. h>

# Define SIZE 4

Struct student_type

{Char name [10];

Int num;

Int age;

Char addr [15];

} Stud [SIZE];

Void save (void)

{FILE * fp;

Int I;

If (fp = fopen ("stu_list", "wb") = NULL)

{

Print ("cannot open file \ n ");

Return;

}

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

If (fwrite (& stud [I], sizeof (struct student_type), 1, fp )! = 1)

Printf ("file write error \ n ");

}

Void main (void)

{Int I;

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

Scanf ("% s % d % s", stud [I]. name, & stud [I]. num, & stud [I]. age, stud [I]. addr );

Save ();

}

10.4.3 fprintf and fscanf

The fprintf and fscanf functions are similar to those of printf and scanf. They are both formatted read/write functions. There is only one difference: the Read and Write objects of fprintf and fscanf functions are not terminals but disk files. The call method is as follows:

Fprintf (File pointer, Format String, output table column );

Fscanf (File pointer, Format String, input table column );

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 following fscanf function can be used to read ASC Ⅱ characters from the disk file: fscanf (fp, "% d, % f", & I, & t );

In this way, the data in the disk file is sent to the variable I, t.

10.4.4 other read/write Functions

I. putw and getw Functions

These two functions are used to read and write a word to a disk file. For example, putw (10, fp) is used to output integer 10 to the file pointed by fp. While I = getw (fp); is used to read an integer from the disk file to the memory and assign it to the integer variable I.

Ii. fgets and fputs Functions

The fgets function reads a string from a specified file. For example, fgets (str, n, fp );

Input n-1 characters from the file pointed to by fp and put them into the str array. If you encounter a linefeed or EOF before the n-1 characters are read, the read operation ends. After the string is read, add the '\ 0' character at the end. The return value of the fgets function is the first address of str.

The fputs function outputs a string from a specified file. For example, fputs ("China", fp );

Output the string "China" to the file pointed to by fp. The first parameter in the fputs function can be a String constant, character array name, or character pointer. The value of the output success function is 0, and the value is non-zero if the output fails.

§ 10. 5 file Positioning

10.5.1 rewind Function

The file has a pointer pointing to the current read/write location. If you read and write a file sequentially and each time you read and write a character, after you write a character, the pointer automatically moves to the next character position. If you want to change this rule and force the position pointer to another specified position, you can use related functions.

The rewind function is used to make the position pointer return the beginning of the file again. This function does not return values.

For example, a disk file is displayed on the screen for the first time, and copied to another file for the second time.

# Include <stdio. h>

Void main (void)

{File * FP1, * fp2;

FP1 = fopen ("file1.c", "R ");

Fp2 = fopen ("file2.c", "W ");

While (! Feof (FP1) putchar (GETC (FP1 ));

Rewind (FP1 );

While (! Feof (P1) putc (GETC (FP1), fp2 );

Fclose (FP1 );

Fclose (fp2 );

}

After the first display on the screen, the position pointer of the file file1.c has pointed to the end of the file, and the value of feof is true. Execute the rewind function to locate the position pointer of the file at the beginning of the file, and restores the feof function value to false.

10.5.2 fseek function and random read/write

If the position pointer is moved in byte order, it is sequential read/write. If you can move the position pointer to another position as needed, you can achieve random read/write. The so-called random read/write refers to reading or writing subsequent characters after reading the previous character, but can read and write any required characters in the file. You can use the fseek function to change the position pointer of a file. The fseek function is called in the form of fseek (file type pointer, displacement, starting point)

The start point is replaced by 0, 1, and 2. 0 indicates the start of the file, 1 indicates the current position, and 2 indicates the end of the file ".

Displacement refers to the number of bytes that are moved forward based on the starting point. Generally, the displacement is long data.

The following are examples of fseek function calls:

Fseek (FP, 100l, 0); move the position pointer to the first 100 bytes away from the file header.

Fseek (fp, 50L, 1); move the position pointer to 50 bytes away from the current position.

Fseek (fp,-10L, 2); returns the position pointer 10 bytes from the end of the file.

10.5.3 ftell Function

The ftell function is used to obtain the current position of the file. If the return value of the ftell function is-1L, an error occurs. For example:

I = ftell (fp );

If (I =-1L) printf ("error \ n"); variable I stores the current location. if a function call error occurs, "error" is output ".

Input a string from the keyboard, convert all lowercase letters into uppercase letters, and output the string to a disk file "test" for saving. The input string is "! "End.

 

From: http://s319.dlut.edu.cn/educ/C_index.htm

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.