Explanation of all file operation functions in C Language fopen, fwrite, fread, fgetc, fputc, fscanf, fprintf,

Source: Internet
Author: User
Tags rewind

Since I have recently used the C language to read and write files, I would like to summarize the following to facilitate later searching.

In c, file operations are implemented by database functions, mainly divided into read and write operations. The following describes the usage of all the file operations in detail:

(1) fopen () function: Open Text

Include header file: # include <stdio. h>

Format: FILE * fopen (const char * path, const char * mode );

Parameters:

Path: path of the file to be opened
Mode: file opening mode
R: open the file in read-only mode. The file must exist.
R + can open a file in read/write mode. The file must exist.
Rb + read/write opens a binary file and allows reading data.
Rt + read/write: open a text file and allow reading and writing.
W. Open and write only the file. If the file exists, the file length is 0, indicating that the file content will disappear. If the file does not exist, the file is created.
W + open the readable and writable file. If the file exists, the file length is cleared to zero, that is, the file content disappears. If the file does not exist, the file is created.
A. Open and write-only files as an attachment. If the file does not exist, the file will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be retained. (EOF reserved)
A + opens readable and writable files by appending them. If the file does not exist, the file will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be retained. (The original EOF is not retained)
Wb only opens or creates a new binary file; only data can be written.
Wb + enables read/write operations or creates a binary file, allowing read and write operations.
Wt + read/write opens or creates a text file; read/write is allowed.
At + read/write opens a text file, allowing you to read or append data at the end of the text.
Open a binary file through AB + read/write, and allow you to read or append data to the end of the file.
Now let's summarize the above file opening methods:
The usage of a file is composed of r, w, a, t, B, and +. The meanings of each character are as follows:
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
Return Value
If the file is successfully opened, the file pointer pointing to the stream is returned. If the file fails to be opened, NULL is returned and the error code is stored in errno.
Description
In general, after opening a file, some operations will be performed to read or write the file. If the file fails to be opened, the subsequent read/write operations will not proceed smoothly () then, make error judgment and handling.
(2) fread () function and fwrite () function :( it can be used to perform operations on data blocks)
1. General call form

Fread (buffer, size, count, fp );

Fwrite (buffer, size, count, fp );

2. Description

(1) 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.

(2) size: the number of bytes to read and write;

(3) count: the number of data items of size bytes to be read and written;

(4) fp: file pointer.

The C language also provides read/write functions for the entire data block. It can be used to read and write a group of data, such as an array element and a value of a structure variable. The call Method for reading data block functions is fread (buffer, size, count, fp). The call Method for writing data block functions is fwrite (buffer, size, count, fp); buffer is a pointer. In the fread function, it indicates the first address to store the input data. In the fwrite function, it indicates the first address of the output data. Size indicates the number of bytes of the data block. Count indicates the number of data blocks to read and write. Fp indicates the file pointer.

For example: fread (fa, fp); it means that four bytes (one real number) are read each time from the file indicated by fp and sent to the real array fa, read five consecutive times, that is, read five real numbers into fa.

(3) fgetc () and fputc (): character read/write Functions

Fgetc function (getc function)
(1) General call form
Ch = fgetc (fp );
(2) Role
Read a character from the specified file, that is, read a character from the file pointed to by fp and assign it to ch.
(3) Return Value
Success: the character returned by the returned value;
Failed: EOF (-1) is returned ).

Fputc function ():

(1) General call form
Fputc (ch, fp );
(2) Role
Write a character to a disk file and output the ch to the file pointed to by fp.
(3) Return Value
Success: The returned value is the output character;
Failed: EOF (-1) is returned ).
Note: The putchar () function is a macro defined by the preprocessing command in stdio. h, namely:
# Define putchar (c) fputc (c, stdout)

4. fgets () and fputs () functions: Read and Write string functions

(1) fgets (): char * fgets (char * str, int num, FILE * fp)

Parameter description: str: stores the string read from the file.

Fp: file pointer of the file to be read

Num: indicates that the string read from the file cannot exceed n-1 characters. Add the end string sign '\ 0' after the last character'

 

(2) fputs (char * s, FILE * stream );
5. fscanf () and fprintf () functions: formatted read/write Functions

(1) fprintf () function: outputs formatted strings to the stream or writes formatted strings to the output stream (file)

Prototype: int fprintf (FILE * stream, const char * format [, argument]…);

Example: fprintf (fp, "% s % d % f", str1, str2, a, B );

(2) fscanf () function: output the content in the file to a variable.

6. ftell () function: Obtain the current read/write position of the stream file. The returned value is the number of bytes that the current read/write position deviates from the file header.

Prototype: long ftell (FILE * fp)

7. fseek () function: Move the fp file read/write position pointer to the specified position.


Int fseek (FILE * fp, long offset, int origin );
Origin refers to the "starting point", which has three constant values, as follows:
The number corresponding to the start point represents the file location
Start with SEEK_SET 0
Current location of SEEK_CUR 1 file
SEEK_END 2 file end
8. rewind () function: points the file pointer to the beginning of a stream.
Prototype: int rewind (FILE * stream );
Example: We generally use the following method to obtain the number of characters in the file:
FILE * fs = fopen ("C: \ 1.txt"," r "); // create a FILE stream
Long length = 0; // declare the file length
Fseek (fs, 0, SEEK_END); // put the internal pointer of the file to the end of the file
Length = ftell (fs); // read the position of the file pointer to obtain the number of characters in the file.
Rewind (fs); // reset the file pointer to the beginning of the file


Author: liangxanhai

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.