C language file reading and writing

Source: Internet
Author: User
Tags fread rewind truncated

In ANSI C, the operation of the file is divided into two ways, that is, streaming file operations and I/O file operations, respectively, described below.
One, streaming file operation
The file operations in this way have an important structure file,file 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 */
File This structure contains the basic properties of the operation of the files, the operation of the file through the structure of the pointer, this kind of file operation commonly used functions see table function function
fopen () Open stream
Fclose () Close the stream
FPUTC () write a character into the stream
FGETC () reads a character from the stream
Fseek () navigates to the specified character in the stream
Fputs () write String to stream
Fgets () reads a line or a specified character from the stream
fprintf () output to stream by format
FSCANF () read by format from stream
Feof () returns True when the end of the file is reached
Ferror () returns its value when an error occurs
Rewind () reset the file locator to the beginning of the file
Remove () Delete file
Fread () reads the specified number of characters from the stream
Fwrite () writes a specified number of characters to the stream
Tmpfile () generates a temporary file stream
Tmpnam () generates a unique file name
Here's a look at these functions
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
Returns 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 table
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:
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 the open file, otherwise it may cause data loss situation, I have often made such a problem 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 benchmark for moving, 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 the ' 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);
12.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");
13.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:
Char x[4230];
FILE *file1=fopen ("C:msdos.sys", "R");
Fread (x,200,12, file1);//read 200*12=2400 bytes altogether
14.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:
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
15.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 ();
16.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);
Second, direct I/o file operation
This is another file operation provided by C, it is through the Direct deposit/fetch file to complete the processing of the file, and the above-mentioned streaming file operation is carried out through the buffer, the streaming file operation is around a file pointer, and such a file operation is around a "handle" to do, what is a handle it? It is an integer that is the only token that the system uses to identify a file (in Windows, the concept of a handle extends to the identity of all device resources). The functions commonly used for such file operations are the following tables, which are defined in io.h and fcntl.h, and the corresponding header files are added when used.
Function description
Open () opens a file and returns a handle to it
Close () closes a handle
Lseek () navigates to the specified location of the file
Read () block reading file
Write () block writes file
EOF () test whether the file is finished
Filelength () Get file length
Rename () Renaming files
Chsize () Change file length
The following is a description of these functions one by one:
1.open ()
Opens a file and returns a handle to it, and if it fails, returns a value less than 0, the prototype is int open (const char *path, int access [, unsigned mode]); The parameter path is the file name to open, access is the open mode, and mode is optional. Represents the properties of a file, mainly used in Unix systems, where the dos/windows parameter has no meaning. The open mode of the file is the following table.
Symbolic meaning symbols meaning symbolic meanings
O_rdonly read-only mode o_wronly write-only mode O_RDWR reading/writing mode
O_ndelay for UNIX systems o_append Append mode o_creat If the file does not exist, create
O_trunc file length truncated to 0 o_excl and o_creat, if the file exists return error o_binary binary mode
O_text text mode
For multiple requirements, you can use the ' | ' operator to connect, such as o_append| The o_text indicates that the file is opened in text mode and append mode.
Example: int Handle=open ("C:msdos.sys", o_binary| O_creat| O_write)
2.close ()
Close a handle, the prototype is int close (int handle), or if 0 is successfully returned
Example: Close (handle)
3.lseek ()
Navigates to the specified position, the prototype is: Long lseek (int handle, long offset, int fromwhere), the parameter offset is the amount of movement, the Fromwhere is the moving datum position, and the value is the same as the previous fseek (). Seek_set: File header; seek_cur: file current position; Seek_end: End of file. This function returns the new access location of the file after execution.
Cases:
Lseek (handle,-1234l,seek_cur);//move the access position forward by 1234 bytes from the current position.
X=lseek (Hnd1,0l,seek_end)///To move the access location to the end of the file, x= the location of the end of the file is the file length
4.read ()
Reading a piece from a file, the prototype is int read (int handle, void *buf, unsigned len), the parameter buf saves the read data, and Len is the byte read. The function returns the bytes actually read out.
Example: Char x[200];read (hnd1,x,200);
5.write ()
Write a piece of data into the file, the prototype is int write (int handle, void *buf, unsigned len), the meaning of the parameter is the same as read (), which returns the actual bytes written.
Example: Char x[]= "I love You"; Write (Handle,x,strlen (x));
7.eof ()
Similar to feof (), test whether the file ends, is returned 1, otherwise returns 0; the prototype is: int eof (int handle);
Example: while (!eof (handle1)) {...};
8.filelength ()
Returns the length of the file, the prototype is long filelength (int handle); equivalent to Lseek (handle,0l,seek_end)
Example: Long x=filelength (handle);
9.rename ()
Rename file, prototype is int rename (const char *oldname, const char *newname); The parameter oldname is the old file name, and NewName is the new filename. Successful return 0
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, returns 0 successfully, otherwise returns 1 if the specified length is less than the length of the file, the file is truncated if the specified length is greater than the length of the file. ‘‘。
Example: Chsize (handle,0x12345);
--------------------------------------------------------------------------------
If you are familiar with the assembly may find this way and assembly language DOS function call handle file operation very much like, such as Open () as a DOS service 3CH function call, in fact, this operation has two types of function is directly with the DOS function to complete, such as _open (), _dos_ Open () and so on. Be interested in self-query BCB help.
As with streaming file operations, this also provides functions for Unicode character manipulation, such as _wopen (), and so on, for wide character programming under 9x/nt, and is interested in helping self-querying BCB.
In addition, this operation also has lock (), unlock (), locking () and other functions for multi-user operation, but in the BCB used not much, I do not introduce, but if you want to use C to write CGI, these are necessary common sense, if you have this requirement, then you have to look at the help.
By the end of this, I have introduced the C-based file operation.

C language file reading and writing

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.