File Operation Function C language (File fputc fgetc fputs fgets fscanf fprintf)
In ansi c, file operations are divided into two methods: stream file operations and I/O file operations, which are described below.
I. Stream File Operations
This file operation has an important structure file, which is defined in stdio. h as follows:
Typedef struct {
Int level;/* fill/empty level of buffer */
Unsigned flags;/* file Status flags */
Char FD;/* file descriptor */
Unsigned char hold;/* ungetc char if no buffer */
Int bsize;/* buffer size */
Unsigned char _ far * buffer;/* Data Transfer Buffer */
Unsigned char _ far * CURP;/* current active pointer */
Unsigned istemp;/* temporary file indicator */
Short token;/* used for validity checking */
} File;/* This is the file object */
the file structure contains the basic attributes of file operations. Operations on files must be performed through the pointer of this structure, common functions for such file operations can be found in the table below function
fopen () Open stream
fclose () Close stream
fputc () write a character to the stream
fgetc () read a character from the stream
fseek () locate the specified character in the stream
fputs () write a string to the stream
fgets () read one or more characters from the stream
fprintf () output to the stream in the format
fscanf () read from stream by format
feof () returns the true value when it reaches the end of the file
returns the value when an error occurs in ferror ()
rewind () reset the file locator to the beginning of the file
remove () delete the file
fread () read the specified number of characters from the stream
fwrite () write a specified number of characters to the stream
tmpfile () to generate a temporary file stream
tmpnam () to generate a unique file name
The following describes these functions
1. fopen ()
fopen is prototype: file * fopen (const char * filename, const char * mode ), fopen implements three functions
open a stream for use
connect a file to the stream
return a filr pointer to the stream
parameter filename point to the file name to open, mode indicates the string in the open state, the values are as follows:
string meaning
"R" open a file in read-only mode
"W" open a file in write-only mode
"a" to append open a file
"R +" open the file in read/write mode, if no file error occurs,
"W +" open the file in read/write mode. If no file is generated, a new file can be opened in text or binary mode, the difference between the two is: in text mode, the carriage return is treated as a character 'n', while in binary mode, it is considered as two characters 0x0d and 0x0a; if you read 0x1b, the text mode considers this as the file Terminator, that is, the binary model does not process the file, and the text mode converts the data in a certain way.
the system opens in text mode by default. You can modify the value of all the Variable _ fmode to modify this setting. For example, _ fmode = o_text; the default mode is set to text mode; _ fmode = o_binary; the default enable mode is binary.
You can also specify the open mode in the mode string. For example, "rb" indicates that the read-only file is opened in binary mode, "W + t" or "WT +" indicates opening the read/write file in text mode.
This function returns a file pointer. Therefore, after declaring a file pointer, you do not need to initialize it. Instead, you can use fopen () to return a pointer and connect it to a specific file, returns null.
example:
file * FP;
If (FP = fopen ("123.456", "WB "))
puts ("file opened successfully");
else
puts ("file opened successfully");
2. fclose ()
Fclose () is used to close files opened with fopen (). Its prototype is int fclose (File * FP). If the file is successful, 0 is returned. If the file is failed, EOF is returned.
InProgramRemember to close the opened file at the end. Otherwise, it may cause data loss. I used to make such a mistake.
Example: fclose (FP );
3. fputc ()
Write a character to the stream. The prototype is int fputc (int c, file * stream). If this character is returned successfully, EOF is returned for failure.
Example: fputc ('x', FP );
4. fgetc ()
Read a character from the stream. The prototype is int fputc (File * stream). If this character is returned successfully, EOF is returned if it fails.
Example: Char struct = fgetc (FP );
5. fseek ()
This function is generally used in files opened in binary mode. It is used to locate the specified position in the stream. The prototype is int fseek (File * stream, long offset, int whence ); if 0 is returned successfully, the offset parameter indicates the number of characters to be moved, and the whence parameter indicates the moving benchmark. The value is
Symbol constant value reference position
Start with seek_set 0
Seek_cur 1 Current read/write location
Seek_end 2 file tail
Example: fseek (FP, 1234l, seek_cur); // move the read/write position 1234 bytes backward from the current position (L suffix indicates a long integer)
Fseek (FP, 0l, 2); // move the read/write location to the end of the file
6. fputs ()
Write a string to the stream. The prototype is int fputs (const char * s, file * stream );
Example: fputs ("I love you", FP );
7. fgets ()
Read a row or a specified character from the stream. The prototype is char * fgets (char * s, int N, file * stream). Read n-1 characters from the stream, unless one line is read, the parameter S is used to receive strings. If the string is successful, the pointer of S is returned. Otherwise, null is returned.
For example, if the text at the current position of a file is as follows:
Love, I have
But ........
If you use
Fgets (str1, 4, file1 );
After execution, str1 = "lov" reads 4-1 = 3 characters.
Fgets (str1, 23, file1 );
Run STR = "love, I have" to read a row (excluding 'n' at the end of the row ').
8. fprintf ()
Input to the stream in the format. Its prototype is int fprintf (File * stream, const char * Format [, argument,...]); the method is the same as printf (), but it is not written to the console, but to the stream.
Example: fprintf (FP, "% 2D % s", 4, "HAHAHA ");
9. fscanf ()
Read from the stream in the format. Its prototype is int fscanf (File * stream, const char * Format [, address,...]); the method is the same as scanf (), but it is not read from the console, but from the stream.
Example: fscanf (FP, "% d", & X, & Y );
10. feof ()
Check whether the end of the file is reached. If it is true, 0 is returned. The prototype is int feof (File * stream );
Example: If (feof (FP) printf ("ended at the end of the file ");
11. ferror ()
The prototype is int ferror (File * stream); returns the most recent stream error.Code, Clearerr () can be used to clear it. The prototype of clearerr () is void clearerr (File * stream );
Example: printf ("% d", ferror (FP ));
12. Rewind ()
Return the current read/write location to the start of the file. The prototype is void rewind (File * stream). In fact, this function is equivalent to fseek (FP, 0l, seek_set );
Example: rewind (FP );
12. Remove ()
Delete the file. The prototype is int remove (const char * filename). The parameter is the name of the file to be deleted. 0 is returned if the file is successfully deleted.
Example: Remove ("C: Io. sys ");
13. fread ()
Read a specified number of characters from the stream. The prototype is size_t fread (void * PTR, size_t size, size_t N, file * stream). The PTR parameter stores the read data, void * pointers can be replaced by pointers of any type, such as char * and int *. Size indicates the number of bytes in each block. N indicates the number of read blocks. If yes, returns the number of actually read parts (not the number of bytes). This function is generally used in files opened in binary mode.
Example:
Char X [4230];
File * file1 = fopen ("C: msdos. sys", "R ");
Fread (x, 200, 12, file1); // read 2400*12 = bytes in total
14. fwrite ()
Corresponds to fread and writes the specified data to the stream. The prototype is size_t fwrite (const void * PTR, size_t size, size_t N, file * stream ); the PTR parameter is the data pointer to be written. The Void * pointer can be replaced by any type of pointer, such as char * and int *. The size is the number of bytes per block; n is the number of blocks to be written. If the number of actually written blocks is returned (not the number of bytes), this function is generally used in files opened in binary mode.
Example:
Char X [] = "I Love You ";
Fwire (x, 6, 12, FP); // write 6*12 = 72 bytes
Write "I love" to the stream FP 12 times, a total of 72 bytes
15. tmpfile ()
The prototype is file * tmpfile (void). A temporary file is generated, opened in "W + B" mode, and a pointer to the temporary stream is returned. If the stream fails, null is returned. At the end of the program, the file will be automatically deleted.
Example: file * fp = tmpfile ();
16. tmpnam ();
Its prototype is char * tmpnam (char * s). A unique file name is generated. In fact, tmpfile () calls this function. The parameter S is used to save the obtained file name, returns the pointer. If the pointer fails, null is returned.
For example, tmpnam (str1 );
2. Direct I/O File Operations
This is another file operation provided by C. It processes the file by directly saving/retrieving the file, and the streaming file operation is carried out through the buffer; streaming file operations are performed around a file pointer, and such file operations are performed around a file's "handle". What is a handle? It is an integer that uniquely identifies a file (in windows, the handle concept is extended to the identifier of all device resources. Common functions for such file operations are listed in the following table. These functions and their symbols are defined in Io. h and fcntl. H, and corresponding header files must be added for use.
Function Description
Open () open a file and return its handle
Close () close a handle
Lseek () locates at the specified position of the file
Read () block Read File
Write () block Write File
Whether the EOF () test file is complete
Filelength () gets the file length
Rename () rename a file
Chsize () changes the file length
The following describes these functions:
1. open ()
Open a file and return its handle. If it fails, a value smaller than 0 will be returned. The prototype is int open (const char * path, int access [, unsigned mode]); the path parameter is the name of the file to be opened, the access mode is open, and the mode is optional. This parameter indicates the properties of a file. It is mainly used in UNIX systems and has no significance in DOS/windows. The file opening mode is shown in the following table.
Symbol Meaning symbol meaning
O_rdonly read-only mode o_wronly write-only mode o_rdwr read/write mode
O_ndelay is used to append o_creat to o_creat in the Unix system. If the file does not exist, it is created.
O_trunc cut the file length to 0 o_excl and o_creat. If the file has an error, the o_binary binary method is returned.
O_text text
You can use the "|" operator to connect to multiple requirements. For example, o_append | o_text indicates opening a file in text mode and append mode.
Example: int handle = open ("C: msdos. sys", o_binary | o_creat | o_write)
2. Close ()
Closes a handle. The prototype is int close (INT handle). If the handle is successful, 0 is returned.
Example: Close (handle)
3. lseek ()
Locate to the specified position. The prototype is long lseek (INT handle, long offset, int fromwhere). The offset parameter is the moving amount, and fromwhere is the moving reference position, the value is the same as fseek (). seek_set: File Header, seek_cur: Current Position of the file, and seek_end: End of the file. This function returns the new file access location after execution.
Example:
Lseek (handle,-1234l, seek_cur); // moves the access location 1234 bytes forward from the current location.
X = lseek (hnd1, 0l, seek_end); // move the access location to the end of the file. x = The End of the file, that is, the length of the file.
4. Read ()
Read a block from the file. The prototype is int read (INT handle, void * Buf, unsigned Len). The parameter Buf stores the read data, and Len is the read byte. The function returns the bytes actually read.
Example: Char X [200]; read (hnd1, X, 200 );
5. Write ()
Write a piece of data to the file. The prototype is int write (INT handle, void * Buf, unsigned Len). The parameter meaning is the same as read (), and the actual written bytes are returned.
Example: Char X [] = "I Love You"; write (handle, X, strlen (x ));
7. EOF ()
Similar to feof (), if the test file ends, 1 is returned; otherwise, 0 is returned; prototype: int EOF (INT handle );
Example: While (! EOF (handle1 )){......};
8. filelength ()
The length of the returned file. The prototype is long filelength (INT handle). It is equivalent to lseek (handle, 0l, seek_end)
Example: long x = filelength (handle );
9. Rename ()
Rename the file. The prototype is int Rename (const char * oldname, const char * newname). The parameter oldname is the old file name and newname is the new file name. 0 is returned successfully.
Example: Rename ("C: config. sys", "C: config. w40 ");
10. chsize ();
Change the file length. The prototype is int chsize (INT handle, Long SIZE). The parameter size indicates the new length of the file. 0 is returned for success; otherwise,-1 is returned, if the specified length is smaller than the file length, the file is truncated. If the specified length is greater than the file length, add ''after the file ''.
Example: chsize (handle, 0x12345 );