Source: Internet
Author: User
Tags fread rewind

reprinted from: 1 fopen

Function prototype: File * fopen (const char * path,const char * mode); return value: When the file is opened successfully, the pointer to the stream will be returned. Returns null if the file fails to open, and the error code exists in errno. fopen_s,_wfopen_s security is enhanced relative to fopen, and if successful returns 0, failure returns the error code of the response errno_t fopen_s (file** pFile, const char *filename, const char *mode); errno_t _wfopen_s (file** pFile, const wchar_t *filename, const wchar_t *mode);

There are 12 ways to use Files




Read-only Open text file


Write-only open or create a text file


Append Open Text File


Read-only open binary file


Write-only to open or create a binary file


Append Open binary file


Read and write Open text file


Read-write open or create a text file


Read and write open text file, can append


Read and write open binary files


Read-write open or binary file creation


Read and write open binaries that can be appended


1. File usage by r,w,a,t,b,+ Six characters, the meaning of each character is:

R (Read) read W (write) write a (append) append + read and write

The t (text) text file can be omitted without writing B (banary) binary files

2. Files opened with "R" can only be read, and the file must already exist.

3. Files opened with "W" can only be written. If the file does not exist, establish it, otherwise, cover it.

4. Files opened with "a" can only be written, and content appended. The file must already exist or an error occurs.

5. When there is an error opening the file, fopen will return NULL.

6. For text files, the conversion to binary form is read into memory and converted to text when writing to the hard drive, which takes a little time to convert. There is no such conversion to read and write binary files.

7. After the file is used, it should be closed to avoid errors such as data loss.

8. Standard input file (keyboard), standard output file (monitor), standard error output (Error message) is open by the system and can be used directly.

2 fread and Fwrite

function Prototypes: size_t fread (void *buffer, size_t size, size_t count, FILE *stream);Function: Reads data from a file stream, reads up to count elements, each element size byte, if the call successfully returns the number of elements actually read to, if not successfully returned 0.        Parameter: Buffer is used to receive the memory address of the data, at least size*count bytes in size.        The size of a single element, in units of the number of bytes count elements, each element being a size byte. Stream input Stream return value: The number of elements actually read. If the return value is not the same as count, the end of the file or an error may occur. function Prototypes: size_t fwrite (const void* buffer, size_t size, size_t count, file* stream);Note: This function operates in binary form and is not limited to text files (1) Buffer: is a pointer to the fwrite, which is the address to get the data, (2) Size: The single-byte number to write the content, and (3) Count: The number of data items to write to the size byte, (4) stream: Target file pointer, (5) returns the number of data items actually written to count. Description: Where is the file written to? This is related to the open mode of the file, if it is w+, it is from the address pointed to by the files pointer start writing, replace the content, the length of the file can be unchanged, the stream's position to move the count number, if A +, from the end of the file to add, file length increased. Fseek is useful for this function, but the fwrite function writes to the user space buffer and is not synchronized to the file, so the memory and file synchronization can be synchronized with the Fflush ("File *fp") function after the modification. Fwrite generally used to write char*,int* cannot be written directly. Because usually we write int to the file you want to see the effect is a number, such as a. but int accounts for 2 or 4 bytes, and when written with Fwrite, an int is written to a file by 2 or 4 bytes, and the file is displayed as a byte-by-byte display, and it does not display 4 bytes consecutively, so it cannot be a single-character word such as the one-size-three. In addition to formatting input fprintf, you can also type conversions, as shown below, but you cannot use fread when reading, only use FSCANF or fscanf_s functions. Char tmp[100] = {0};_itoa_s (int, TMP, ten), Fwrite (TMP, STRLEN (TMP), 1, file); Fwrite ("\ t", 1, 1, file); memset (sbuf,0,100); relative to the use of formatted input, if the writing data is more cumbersome (5 sentences using 1 words can be replaced) fprintf (file, "%d", int) ; 3 fprintf and fscanf

int fprintf (FILE *stream,const char *format,[argument])

The fprintf () function sends information (parameters) to the file specified by stream (stream) according to the specified format (format). fprintf () can only work with printf (). The return value of fprintf () is the number of characters in the output and a negative value is returned when an error occurs.

%d decimal signed integer

%i an integer

%u decimal unsigned integer

%f floating Point

%s string

%c single character

%p the value of the pointer

Floating-point numbers in the form of%e indices

%x,%x unsigned integer in hexadecimal notation

%o unsigned integer represented in octal

%g automatic selection of appropriate representations

An integer that%n equals the number of characters read

%[] a character set

Percent of a precision symbol

int fscanf (file* stream,const char *format,[argument ...]);

Return value: Integer, number of parameters successfully read in

int fscanf_s (file* stream,const char *format,[argument ...]);

4 fclose,ferror,feof

fclose (file pointer) returns 0 if it is closed normally, otherwise nonzero.

Get error messages from Ferror and feof or detect if end of file is reached

feof file End returns non 0, otherwise returns 0

5 fseek

int fseek (FILE *stream, long offset, int origin);

The first parameter stream is a file pointer

The second parameter offset is offset, positive number indicates positive offset, negative is negative offset

The third parameter, origin, sets the offset from where the file begins, possibly with a value of: Seek_cur, Seek_end, or Seek_set

Seek_set file start seek_cur current position seek_end end of file

6 Rewind,ftellPrototype: void Rewind (file *stream); function: Points the file pointer back to the beginning of a stream, equivalent to Fseek (stream, 0L, Seek_set) prototype: Long Ftell (file * FP) function: The current read and write location of the streaming file is obtained, and its return value is the number of bytes from the file header that the current read and write position deviates from. Example: In general we will get the number of characters in the file by using the following method: File *fs=fopen ("C:\1.txt", "R"),//Create stream Fseek (fs,0,seek_end),//Place the internal pointer of the file on the last side of the file length=f Tell (FS);//Read the position of the file pointer, get the number of file characters rewind (fs);//Reset the file pointer to the front of the file

7 fgetc/fputc/fgets/fputs

fgetc function

(1) General call Form CH=FGETC (FP);

(2) The function reads a character from the specified file, i.e. reads a word assigned to CH from the file pointed to by the FP.

(3) Return value

Success: The resulting character of the return value; failure: Returns EOF (-1).

FPUTC function

(1) General call Form FPUTC (CH,FP);

(2) The function writes a character to the disk file, and the character ch is output to the file that the FP points to.

(3) Return value

Success: The return value is the character of the output; failure: Returns EOF (-1).

Description: The function Putchar () is a macro defined in stdio.h with a preprocessing command, namely:

#define PUTCHAR (c) FPUTC (c,stdout)

Char *fgets (char *str, int num, FILE *FP)

Parameter description: str: Save a string read from a file

FP: file pointer to a file to be read

Num: Indicates that a string that is read from a file does not exceed n-1 characters. After the last character that is read, add the string end flag ' \ s '

int fputs (const char * s,file * stream)

Function: Writes a string to the specified file (does not automatically write the string end tag ' \ "). When a string is successfully written, the position pointer of the file is automatically moved back, and the function returns a non-negative integer, otherwise eof (the symbolic constant with a value of-1) is returned.


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: 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.