C C + + IO

Source: Internet
Author: User
Tags fread rewind truncated

C-based file operations
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 in the header file 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 to open a read-only file, the file must exist.
r+ open a writable file, the file must exist.
rb+ Read and write open a binary file, allowing only read and write data.
rt+ Read and write open a text file that allows reading and writing.
W Open Write-only file, if the file exists then the file length is clear to 0, that is, the contents of the file will disappear. If the file does not exist, the file is created.
w+ Open a read-write file, if the file exists then the file length is clear to zero, that is, the contents of the file will disappear. If the file does not exist, the file is created.
A write-only file opens in an additional way. If the file does not exist, the file will be created, and if the file exists, the data written will be added to the end of the file, that is, the original content of the file will be retained. (EOF character reserved)
A + opens readable and writable files in an additional way. If the file does not exist, the file will be created, and if the file exists, the data written will be added to the end of the file, that is, the original content of the file will be retained. (the original EOF character is not preserved)
WB only writes Open or create a new binary file; Only write data is allowed.
wb+ read-write open or create a binary file that allows reading and writing.
wt+ read-write open or create a text file;
at+ Read and write open a text file that allows you to read or append data at the end of the text.
ab+ Read and write open a binary file that allows you to read or append data at the end of the file.

A file can be opened in text mode or binary mode, the difference is that the carriage return in the text mode is treated as a character ' \ n ', 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.

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 ' \ 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:

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:

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);

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);


--------------------------------------------------------------------------------------------------------------- ----------------------------------------------

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

C + +-based file operations

In C + +, there is a stream in this class, all I/O is based on this "stream" class, including the files we want to know i/o,stream this class has two important operators:

1. Insertion device (<<)
Outputs data to the stream. For example, the system has a default standard output stream (cout), usually refers to the display, so,cout<< "write Stdout" << ' \ n '; means the string "write Stdout" and the newline character (' \ n ') Output to the standard output stream.

2. Extraction Device (>>)
Enter data from the stream. For example, the system has a default standard input stream (CIN), which is normally referred to as the keyboard, so,cin>>x; is the data that reads a specified type (that is, the type of the variable x) from the standard input stream.

In C + +, the operation of the file is implemented through the subclass FStream (file stream) of the stream, so to manipulate the file in this way, the header file fstream.h must be added. The following is the process of this type of file operation one by one.

First, open the file
In the FStream class, there is a member function open (), which is used to open the file, and its prototype is:

void Open (const char* filename,int openmode,int access);

Parameters:

FileName: The file name to open
Mode: How to open a file
Access: Open the properties of a file
The way you open a file is defined in class iOS (the base class for all streaming I/O classes) and the values that are commonly used are as follows:

Ios::app: Open file in Append mode
Ios::ate: The file is opened and positioned to the end of the file, Ios:app contains this property
Ios::binary: Open the file in binary mode, the default way is text mode. The difference between the two methods is shown in the previous article
Ios::in: File opens in input mode (file = = Program)
Ios::out: File opens in output mode (program = = file)
Ios::nocreate: Do not create file, so file does not exist when open failed
Ios::noreplace: Do not overwrite file, so if file exists failure when opening file
Ios::trunc: If the file exists, set the file length to 0
You can use "or" to connect the above attributes, such as Ios::out|ios::binary.

The properties of the open file are values:

0: Normal file, open access
1: Read-only files
2: Implied file
4: System files
You can use "or" or "+" to connect the above properties, such as 3 or 1|2 to open the file with read-only and implied properties.

Example: Opening a file as a binary input C:\Config.sys

FStream file1;
File1.open ("C:\\config.sys", ios::binary|ios::in,0);

If the open function has only one parameter for the file name, it is opened with a read/write normal file, namely:

File1.open ("C:\\config.sys"); <=>file1.open ("C:\\config.sys", ios::in|ios::out,0);

In addition, FStream also has the same constructor as open (), and for the above example, you can open the file when you define it:

FStream file1 ("C:\\config.sys");

In particular, FStream has two subclasses: ifstream (input file stream) and Ofstream (OUTPU file stream), ifstream default to open the file as input (Files = = program), Ofstream, by default, opens the file in the output mode.

Ifstream file2 ("C:\\pdos.def");//Open file as input
Ofstream file3 ("c:\\x.123");//Open file in output mode

Therefore, in the actual application, according to the needs of different, choose different classes to define: If you want to open in the input mode, use Ifstream to define, if you want to open in the output, use Ofstream to define, if you want to open in the input/output mode, use FStream to define.

Second, close the file
Open files must be closed after use, FStream provides a member function close () to complete this operation, such as: File1.close (), the file1 connected file is closed.

Iii. Read and write files
Read and write files are divided into text files and binary files read, for the text file reading is relatively simple, with the insertion and the profiler can be, and for the binary reading is more complicated, the next to the detailed introduction of these two ways

1. Reading and writing of text files
Reading and writing text files is simple: Use the plug-in (<<) to output to the file, and use the Profiler (>>) to import from the file. Suppose the file1 is opened as input, File2 is opened with output. Examples are as follows:

file2<< "I love You";//write The string "I love You" to the file
int i;
file1>>i;//Enter an integer value from the file.

This way there is a simple format, such as the output can be specified as 16 and so on, the specific format has the following

operator function input/output
Dec formatted as decimal numeric data input and output
Endl outputs a newline character and refreshes the stream output.
Ends output a null character output
Hex formatted as hexadecimal numeric data input and output
Oct formatted as octal numeric data input and output
setpxecision (int p) Sets the precision bit output of a floating-point number

For example, to use 123 as the hexadecimal output:file1<<<123; to 3.1415926 with 5-bit precision output: file1<<<3.1415926.

2. Read and write binary files
①put ()
The put () function writes a character to the stream, and its prototype is Ofstream &put (char ch), which is simpler to use, such as File1.put (' C '), which is to write a character ' C ' to the stream.

②get ()
The Get () function is more flexible and has 3 commonly used overloaded forms:

One is the form that corresponds to the put (): Ifstream &get (char &ch), the function is to read a character from the stream, the result is saved in the reference CH, if the end of the file, the null character is returned. such as File2.get (x); indicates that a character is read from a file and the read word is characters in X.

Another overloaded form of the prototype is: int get (); This form returns a character from the stream, if it reaches the end of the file, it returns EOF, such as X=file2.get (), and the previous example function is the same.

Another form of prototyping is: Ifstream &get (char *buf,int num,char delim= ' \ n '), which reads characters into an array pointed to by BUF until NUM characters are read or a character specified by Delim is encountered. If you do not use the Delim parameter, the default newline character ' \ n ' will be used. For example:

File2.get (str1,127, ' a ');//reads a character from a file to a string str1, terminating when the character ' A ' is encountered or 127 characters are read.

③ read and write data blocks
To read and write binary data blocks, use the member function read () and the Write () member functions, which are prototyped as follows:

Read (unsigned char *buf,int num);
Write (const unsigned char *buf,int num);

Read () reads num characters from a file into the cache pointed to by buf, and if it is at the end of the file when NUM characters have not been read, you can use the member function int gcount () to get the number of characters actually read, while write () writes NUM characters from the cache pointed to by BUF to a file , it is important to note that the type of cache is unsigned char *, which may sometimes require a type conversion.

Cases:

unsigned char str1[]= "I love You";
int n[5];
Ifstream in ("xxx.xxx");
Ofstream out ("yyy.yyy");
Out.write (Str1,strlen (STR1));//write the string str1 all to Yyy.yyy
In.read ((unsigned char*) n,sizeof (n));//Read the specified integer from the xxx.xxx, note the type conversion
In.close (); Out.close ();

Iv. Detection of EOF
The member function EOF () is used to detect whether the end of the file is reached, or 0 if the end of the file returns a value other than 0. The prototype is an int eof ();

Example: if (in.eof ()) ShowMessage ("has reached the end of the file!") ");

V. Positioning of documents
Unlike the C file operation, the C + + I/O system manages two pointers that are associated with a file. One is a read pointer, which shows the position of the input operation in the file, and the other is the position of the write pointer, which is the next write operation. Each time the input or output is executed, the corresponding pointer changes automatically. So, C + + file positioning is divided into read position and write location, corresponding member function is SEEKG () and SEEKP (), SEEKG () is set to read position, SEEKP is set write position. Their most common form is as follows:

IStream &AMP;SEEKG (Streamoff offset,seek_dir origin);
Ostream &AMP;SEEKP (Streamoff offset,seek_dir origin);

Streamoff, defined in iostream.h, defines the maximum value that offset offset can achieve, Seek_dir represents the base position of the move, and is an enumeration with the following values:

Ios::beg: File Start
Ios::cur: File Current Location
Ios::end: End of File
These two functions are typically used in binary files because the text file may be different from the expected value because the system interprets the characters.

Cases:

FILE1.SEEKG (1234,ios::cur);//Move the read pointer of the file backward from the current position by 1234 bytes
FILE2.SEEKP (1234,ios::beg);//Move the file's write pointer back 1234 bytes from the beginning of the file

C C + + IO

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.