File Operations in C

Source: Internet
Author: User
Tags rewind

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. All FILE operations must be performed through the pointer of this structure. For common functions of such FILE operations, see the following table functions.
Fopen () Open stream
Fclose () Close the stream
Fputc () writes a character to the stream
Fgetc () reads a character from the stream
Fseek () locates the specified character in the stream
Fputs () writes a string to a stream
Fgets () reads a row or a specified character from the stream.
Fprintf () Outputs Data to the stream in the format
Fscanf () reads data from the stream in the format
Returns the true value when feof () reaches the end of a file.
Returns the value of ferror () When an error occurs.
Rewind () resets the file locator to the beginning of the file
Remove () delete an object
Fread () reads a specified number of characters from a stream
Fwrite () writes a specified number of characters to the stream.
Tmpfile () generates a temporary file stream
Tmpnam () generates a unique file name


The following describes these functions.

1. fopen ()
The fopen 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
Returns a FILR pointer to the stream.
The filename parameter points to the name of the file to be opened. 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" open the file in append Mode
"R +" open the file in read/write mode. If no file error occurs
"W +" opens a file in read/write mode. If no file is generated, a new file is generated.

A file can be opened in text or binary mode. The difference between the two is that in text mode, carriage return is treated as a character 'n ', the binary mode considers it to be two characters: 0x0D and 0x0A. If you read 0x1B in the file, the text mode considers it to be the file Terminator, that is, the binary model does not process the file, the text method converts the data in a certain way.

By default, the system is enabled in text mode. You can modify the value of all variables _ fmode to modify this setting. For example, _ fmode = O_TEXT; then, 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, so it does not need to be initialized after declaring a FILE pointer. Instead, it uses fopen () to return a pointer and connect it to a specific FILE. If it succeeds or fails, NULL is returned.

Example:

FILE * fp;
If (fp = fopen ("123.456", "wb "))
Puts ("file opened successfully ");
Else
Puts ("file opening success or failure ");

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.

When the program ends, remember to close the opened file. 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). The latest error code of the returned stream can be cleared by clearerr (). 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.
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 );

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.