C's file read and write

Source: Internet
Author: User
Tags rewind


1.fopen ()


Fopen's prototype is: File *fopen (const char *filename,const char *mode), fopen implements three functions: open a stream for use, connect a file to this stream, and return a FILR pointer to this stream.

The parameter filename points to the name of the file to be opened, and mode represents the open string, which takes the following values:

string meaning

"R" opens the file as read-only

"W" to open files in write-only mode

"A" opens the file in Append mode

"R+" opens the file in read/write mode, such as no file error

"w+" opens a file in read/write mode, such as no file generation new file

A file can be opened in text or binary mode, where the difference is that the carriage return is treated as a character '/n ' in text mode, while the binary mode considers it to be two characters 0x0d,0x0a; if you read 0x1b in a file, the text pattern will consider it a file terminator, That is, the binary model does not process the file, and the text is converted to the data in a certain way.

The default is to open in text mode, you can modify the value of all variable _fmode to modify this setting, such as _fmode=o_text; set the default open mode to text mode, and _fmode=o_binary, set the default open mode is Binary mode.

We can also specify an open pattern in the pattern string, such as "RB" to open a read-only file in binary mode, "W+t" or "wt+" to open a read/write file in text mode.

This function returns a file pointer, so declare a file pointer without initialization, and instead use fopen () to return a pointer and connect to a particular file, or null if it succeeds.
Cases:
The following is a reference fragment:
FILE *FP;
if (Fp=fopen ("123.456", "WB"))
Puts ("Open file succeeded");
Else
Puts ("Open file Success");


2.fclose ()


The function of fclose () is to close the file opened with fopen (), whose prototype is: int fclose (file *fp) and, if successful, returns 0, and the failure returns EOF.

At the end of the program must remember to close open files, otherwise it may cause data loss situation, I have often made such a mistake before.

Example: fclose (FP);

3.FPUTC ()


Writes a character to the stream, the prototype is an int fputc (int c, FILE *stream); Successfully returns this character, and the failure returns EOF.

Example: FPUTC (' X ', FP);

4.FGETC ()
Read a character from the stream, the prototype is an int FPUTC (FILE *stream); Successfully returns this character, and the failure returns EOF.

Example: Char ch1=fgetc (FP);

5. Fseek ()


This function is generally used in binary mode open files, the function is to navigate to the location specified in the stream, the prototype is an int fseek (file *stream, long offset, int whence), if 0 is successfully returned, the parameter offset is the number of characters moved, Whence is the base of the move, and the value is:

Symbol constant Value datum position

Seek_set 0 File Start

Seek_cur 1 Current Read and write locations

Seek_end 2 File Trailer

Example: Fseek (fp,1234l,seek_cur);//Move the Read and write position backward from the current position 1234 bytes (l suffix indicates a long integer)

Fseek (fp,0l,2);//Move the read-write position to the end of the file

6.fputs ()

Write a string into the stream, prototype int fputs (const char *s, FILE *stream);

Example: Fputs ("I Love You", FP);

7.fgets ()


Reads a line or a specified character from the stream, and the prototype is a char *fgets (char *s, int n, FILE *stream); Read n-1 characters from the stream, unless a line is read, the parameter S is to receive the string, and if successful returns a pointer to s, otherwise null is returned.

Example: If the text of a file's current position is as follows:
Love, I had

But .....

If you use

Fgets (STR1,4,FILE1);

The str1= "Lov" after execution, reads 4-1 = 3 characters, and if a

Fgets (STR1,23,FILE1);

Then executes str= "Love, I has", reading a line (excluding '/n ' at the end of the line).

8.fprintf ()


Entered into the stream by format, its prototype is int fprintf (FILE *stream, const char *format[, argument, ...]); The usage is the same as printf (), but it's not written to the console, but to the stream.

Example: fprintf (FP, "%2d%s", 4, "hahaha");

9.FSCANF ()


Read by format from Stream, its prototype is int fscanf (FILE *stream, const char *format[, address, ...]); The usage is the same as scanf (), but not read from the console, but read from the stream.

Example: fscanf (FP, "%d%d", &x,&y);

10.feof ()


Detects whether the end of the file is returned, is true, otherwise returns 0, whose prototype is int feof (file *stream);

Example: if (feof (FP)) printf ("To End of file");

11.ferror ()


The prototype is an int ferror (file *stream), which returns the nearest error code for the stream, which can be cleared by Clearerr (), and Clearerr () is a void Clearerr (file *stream);

Example: printf ("%d", Ferror (FP));

12.rewind ()


The current read and write position is returned to the file, the prototype is void Rewind (file *stream), in fact, this function is equivalent to fseek (Fp,0l,seek_set);

Example: Rewind (FP);

13.remove ()


Delete file, prototype is int remove (const char *filename); The parameter is the name of the file to be deleted and successfully returns 0.

Example: Remove ("C://io.sys");

14.fread ()


Reads the specified number of characters from the stream, the prototype is size_t fread (void *ptr, size_t size, size_t N, FILE *stream), the parameter PTR is the data that holds the read, and the void* pointer can be replaced by any type of pointer, such as char*, int * And so on to replace; size is the number of bytes per block, n is the number of blocks read, and if successful, returns the number of blocks actually read (not the number of bytes), this function is typically used in binary mode open files.

Cases:
The following is a reference fragment:
Char x[4230];
FILE *file1=fopen ("C://msdos.sys", "R");
Fread (x,200,12, file1);//read 200*12=2400 bytes altogether

15.fwrite ()


Corresponding to the fread, the specified data is written to the stream, the prototype is size_t fwrite (const void *ptr, size_t size, size_t N, FILE *stream), and the parameter PTR is the data pointer to be written, void* Pointers can be replaced by any type of pointer, such as char*, int *, and so on; size is the number of bytes per block, n is the number of blocks to write, and if successful, returns the number of blocks actually written (not the number of bytes), this function is typically used in binary mode open files.

Cases:
The following is a reference fragment:
Char x[]= "I love You";
Fwire (x, 6,12,FP);//write 6*12=72 bytes
Will write "I love" to the stream FP 12 times, total 72 bytes

16.tmpfile ()


Its prototype is file *tmpfile (void); Generates a temporary file, opens in a "w+b" mode, and returns a pointer to this temporary stream if the failure returns NULL. At the end of the program, the file will be automatically deleted.

Example: FILE *fp=tmpfile ();

17.tmpnam ();


Its prototype is Char *tmpnam (char *s); Generates a unique file name, in fact Tmpfile () calls this function, the parameter s is used to save the resulting file name, and returns the pointer, if it fails, returns NULL.

Example: Tmpnam (STR1);

1. There are several concepts to understand first:

File: A collection of data stored on disk by a certain rule.

File name: A string that uniquely identifies a disk file. Form: Drive Letter:/path/file name. extension

Text file:: Data is stored on disk in ASCII form of its numeric characters, one byte at a byte.

Binary files: Data is stored in binary form on disk.

Device files: input/output devices

Standard input File: keyboard

Standard output file/Standard error output file: Monitor

FILE-type pointers: The C language manages the read and write of files through a structured pointer called file. FILE *< Variable name >

File open and close: The file operation first establishes the relationship between the file and the file pointer, then the file read and write. The process of establishing a link between a file and a file pointer is to open the file. Terminating this connection is the closing of the file.

File structure: defined in 〈stdio.h〉. The form is as follows:

typedef struct

{

int _fd; /* File code */

int _cleft; /* The number of bytes left in the file buffer */

int _mode; /* File Usage mode */

Char *NEXTC; /* The next byte address to be processed, i.e. the file internal pointer */

Char *buff; /* File buffer first address */

}file;

2. The main operation function with corresponding use

1) Opening and closing of the file:

#include <stdio.h>

FILE *FP;

fp = fopen (char* filename, char* made);

if (fp = = NULL)

{

Exit (0);

}

Fclose (FP)

mode and types are:

R: Open a text file for reading data, the file does not exist, then NULL is returned

W: Create a text file for writing. Discard original Content

A: Open or create a text file that appends data to the end of the file

r+: Updating data

w+: Update data, Discard legacy content

A +: Update the data and write the data appended to the end of the file.

Binary is appended with "B"

File-type pointers for standard input/output files: stdin, stdout, stderr

2) Read and write the file:

Writes a character to a file or reads a character from a file: The internal pointer of the file is automatically moved down to a writable location

int FPUTC (char ch, FILE *FP);

int fgetc (FILE *fp)

Write a row of data to a file, or read a row of data:

char * fputs (char *str, FILE *FP)

char * fgets (char *str, int n, FILE *fp); Read N-1 characters, nth character complement '/0 '

Writes several data of the specified number of bytes to the file, or reads the file.

int fwrite (char * buf, unsigned size, unsigned n, FILE *FP); Size the number of bytes per data, n data.

int fread (char *buf, unsigned size, unsigned n, FILE *FP);

Writes data in the specified format to a file or reads data in a specified format

int fprintf (FILE *fp, Char *format, e1,e2,...... en);

int fscanf (FILE *fp, Char *format, e1,e2,...... en);

3) Determination of file location and pointer management.

End of file test: int feof (*FP); The end of the currently reached file returns non 0, otherwise returns 0

Different computer systems use different keyboard combinations to form the terminator of the file. IBM PC and its compatible machine are <ctrl> + Z

Reposition the internal pointer of the file to the beginning of the file int rewind (file *fp);

Position the internal pointer of the file to the specified location: int fseek (file *fp, long offset, int from);

The from is the starting point of the positioning.

Seek_set 0 Starting with the file header

Seek_cur 1 starting from the current position of the inside pointer of the file

Seek_end 2 starts at the end of the file

Offset is the number of faintly bytes from the starting point, greater than 0 means the end of the file, 0 does not move,

File operation error Measurement int ferror (*FP);

Used to test the correctness of the last operation of the file pointed to by the FP. Error returned to non 0, not yet returned 0

4) Deletion of files

int remove (char * filename);

3. Some knowledge points I didn't think of before.

Char ch;

ch = getchar () function equivalent to ch = fgetc (stdin) function equivalent to scanf ("%c", ch) function equivalent to fscanf (stdin, "%c", ch)

Putchar (CH) function equivalent to printf ("%c", ch) function equivalent to FPUTC (stdout) function equivalent to fprintf (stdout, "%c", ch)

C's file read and write

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.