Operations on files in C Language

Source: Internet
Author: User
Tags rewind
13.3 open and close a file
Open the file before performing read/write operations, and close it after use. Opening a file is actually about creating information about the file and directing the file pointer to the file for other operations. If the file is closed, the connection between the pointer and the file is closed, and operations on the file are prohibited.

In C, file operations are performed by library functions. This chapter describes the main file operation functions.

13.3.1 open a file (fopen function)
The fopen function is used to open a file. The Calling method is generally as follows:

File pointer name = fopen (file name, file method );

Where,

"File pointer name" must be a pointer variable described as file type;

"File name" is the name of the opened file;

"File Usage" refers to the file type and operation requirements.

The "file name" is a String constant or a string array.

For example:

File * FP;

Fp = ("file a", "R ");

It means to open file a in the current directory, only allow "read" operations, and direct FP to the file.

Another example:

File * fphzk

Fphzk = ("C: \ hzk16", "rb ")

It means to open the file hzk16 under the root directory of drive C, which is a binary file and only allows read operations in binary mode. The first character in the two Backslash "\" represents the escape character, and the second is the root directory.

There are 12 methods to use files. Their symbols and meanings are given below.

File Usage
Meaning

"RT"
Read-only opens a text file and only allows reading data

"WT"
Only write to open or create a text file, only data can be written

""
Append a text file and write data at the end of the file.

"RB"
Read-only open a binary file and only allow reading data

"WB"
Only write to open or create a binary file, only data can be written

"AB"
Append a binary file and write data at the end of the file.

"RT +"
Read and Write

"WT +"
Read/write to open or create a text file, allowing read/write

"At +"
Open a text file, allow reading, or append data at the end of the file.

"RB +"
Open a binary file for read and write operations.

"WB +"
Read/write to open or create a binary file, allowing read and write

"AB +"
Open a binary file, allow reading, or append data at the end of the file.

The usage of files is described as follows:

1) the usage of the file is comprised of R, W, A, T, B, and +. The meaning of each character is:

R (read): Read

W (write): Write

A (append): append

T (text): Text File, can be omitted without writing

B (banary): Binary File

+: Read and Write

2) When you use "R" to open a file, the file must already exist and can only be read from the file.

3) A file opened with "W" can only be written to this file. If the opened file does not exist, the file is created with the specified file name. If the opened file already exists, delete the file and create a new file.

4) to append new information to an existing file, you can only open the file in "A" mode. However, this file must exist at this time; otherwise, an error will occur.

5) if an error occurs when opening a file, fopen returns a null pointer value. In the program, this information can be used to determine whether to complete the file opening and handle it accordingly. Therefore, the following sections are commonly used to open files:

6) if (FP = fopen ("C: \ hzk16", "rb") = NULL)

{

Printf ("\ nerror on Open c :\\ hzk16 file! ");

Getch ();

Exit (1 );

}

The meaning of this program is that if the returned pointer is null, it indicates that the hzk16 file under the root directory of the C drive cannot be opened, the message "error on Open c: \ hzk16 file!" is displayed !", The next line of getch () is used to input a character from the keyboard, but is not displayed on the screen. Here, this row is used to wait, only when the user clicks any lose function from the keyboard, the return value is 0. If a non-zero value is returned, an error occurs.

13.4 file read/write
Reading and writing a file is the most common file operation. The C language provides a variety of functions for reading and writing files:

· Character read/write functions: fgetc and fputc

· String read/write functions: fgets and fputs

· Data block read/write functions: freed and fwrite

· Formatted read/write functions: fscanf and fprinf

The following sections describe them respectively. The above functions must contain the header file stdio. h.

13.4.1 character read/write functions fgetc and fputc
A read/write function is a read/write function in bytes. One character can be read from or written to a file each time.

1. Read character function fgetc

The fgetc function is used to read a character from a specified file. The function is called in the form:

Character variable = fgetc (File pointer );

For example:

Ch = fgetc (FP );

It means reading a character from the open file FP and sending it to Ch.

The usage of the fgetc function is described as follows:

1) In the fgetc function call, the read file must be opened in read or read/write mode.

2) The result of reading characters can also be not assigned a value to the character variable,

For example:

Fgetc (FP );

However, the read characters cannot be saved.

3) There is a position pointer inside the file. It is used to point to the current read/write bytes of the file. When a file is opened, the pointer always points to the first byte of the file. After the fgetc function is used, the position pointer moves one byte backward. Therefore, you can use the fgetc Function Multiple times to read multiple characters. Note that the file pointer is not the same as the position pointer inside the file. The file Pointer Points to the entire file and must be defined in the program. As long as no value is assigned again, the file pointer value remains unchanged. The position pointer inside the file is used to indicate the current read/write position inside the file. Every read/write time, the pointer moves backward. It does not need to be defined in the program, but is automatically set by the system.

Example 13.1← read the file c1.doc and output it on the screen.

# Include <stdio. h>
Main ()
{
File * FP;
Char ch;
If (FP = fopen ("d :\\ jrzh \ example \ c1.txt", "RT") = NULL)
{
Printf ("\ ncannot open file strike any key exit! ");
Getch ();
Exit (1 );
}
Ch = fgetc (FP );
While (Ch! = EOF)
{
Putchar (CH );
Ch = fgetc (FP );
}
Fclose (FP );
}

The function of this program is to read characters from files one by one and display them on the screen. The program defines the file pointer FP, opens the file "D: \ jrzh \ example \ ex1_1.c" as a read text file, and points the FP to the file. If an error occurs while opening the file, a prompt is displayed and the program is exited. The program reads one character in line 3 and then enters the loop. As long as the characters read are not the end mark of the file (each top, then the next character is read. Every read, the position pointer inside the file is backward ?? This program will display the entire file.

2. Write the character function fputc

Functions of the fputc function ?? Is:

Fputc (character volume, file volume or variable, for example:

Fputc ('A', FP );

The usage of putc functions should also be described as follows:

1) The written file can be opened in the write, read/write, or append mode, and in the write or read/write mode ?? The write character starts from the beginning of the file. If you want to retain the original file content, what words do you want to write ?? If the file to be written does not exist, the file is created.

2) each time a character is written, the internal position pointer of the file moves one byte backward.

3) The fputc function has a return value. If the write is successful, the written character is returned. Otherwise, an EOF is returned. This can be used to determine the write operator, write a file, and read the file content and display it on the screen.

# Include <stdio. h>

Main ()

{

File * FP;

Char ch;

If (FP = fopen ("d :\\ jrzh \ example \ string", "WT +") = NULL)

{

Printf ("cannot open file strike any key exit! ");

Getch ();

Exit (1 );

}

Printf ("input a string: \ n ");

Ch = getchar ();

While (Ch! = '\ N ')

{

Fputc (CH, FP );

Ch = getchar ();

}

Rewind (FP );

Ch = fgetc (FP );

While (Ch! = EOF)

{

Putchar (CH );

Ch = fgetc (FP );

}

Printf ("\ n ");

Fclose (FP );

}

The second line in the program opens the string file in the form of reading and writing text files. The program reads a character from the keyboard in line 3 and then enters the loop. When the character is not a carriage return, the program writes the character into the file and continues to read the next character from the keyboard. Each time one character is entered, the internal position pointer of the file moves one byte backward. After writing, the pointer is directed to the end of the file. To read the file from the beginning, you must move the pointer to the file header. The program's 19th-line rewind function is used to move the internal position pointer of the file referred to by FP to the file header. Lines 20th to 25 are used to read a row of content from the file.

[Example 13.3] copy the file marked by the previous file name in the command line parameter to the file marked by the last file name, if there is only one file name in the command line, the file will be written to the standard output file (Display.

# Include <stdio. h>

Main (INT argc, char * argv [])

{

File * FP1, * fp2;

Char ch;

If (argc = 1)

{

Printf ("have not enter file name strike any key exit ");

Getch ();

Exit (0 );

}

If (FP1 = fopen (argv [1], "RT") = NULL)

{

Printf ("cannot open % s \ n", argv [1]);

G

Hofman 22:04:23 comment: 49 reading: 146093 reference: 0

Comment @ 09:44:06 my contents tonight are incomplete.

No question @ 14:08:19 will be easy, difficult to use !!!

The object to be read is not enough. @ 11:33:48 for example, if you open the file in R + mode, the file contains 100 records, and the record content is a struct.
Struct bankclient
{
Int count;
Char name [];
Float name;
}
Add the content after the initial value {0, "", 0}, one hundred;
Inhale ate data in the file {28001, Dashan, 32.0}, {28008, DFD, 321.2}, {28005, fdjg, 54.5}, and read the data.
Why is it read in the order of 28001,280 05.28008? These Hidden values are perfectly added.

No question @ 2012-03-17 18:05:55 Chen Xuan learned it. Thank you for sharing it.

No question @ 09:08:45 in C, how to treat the content in the array as a file name

No question @ 00:55:24 what teaching materials do I need to buy for computer learning?

Find an error for the landlord @ 16:49:05 sky # include <stdio. h>

Main ()

{

File * FP;

Char ch;

If (FP = fopen ("d :\\ jrzh \ example \ string", "WT +") = NULL) // change it to If (FP = fopen ("D: \ jrzh \ example \ string", "RT +") = NULL) otherwise, you cannot get the troubleshooting information !! Understand the meanings of W and R !!

{

Printf ("cannot open file strike any key exit! ");

Getch ();

Exit (1 );

}

Printf ("input a string: \ n ");

Ch = getchar ();

While (Ch! = '\ N ')

{

Fputc (CH, FP );

Ch = getchar ();

}

Rewind (FP );

Ch = fgetc (FP );

While (Ch! = EOF)

{

Putchar (CH );

Ch = fgetc (FP );

}

Printf ("\ n ");

Fclose (FP );

}

* ************************************ Create files in C Language to the specified folder
File * fp = fopen ("C: \ ABC \ a.txt", "W");/* Open the.txt file in the C: \ ABC \ folder to write information. If the file does not exist, create this file at this location *

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.