Detailed usage of C language file read/write operations

Source: Internet
Author: User
Tags fread rar

Detailed usage of C language file read/write operations


C file operations
1. Read one file to another, and use "(ch = getc (fp ))! = EOF "to determine whether the file ends. If

The file size is the same as the size of the original file.

Text or binary files, the original file ends after reading.
2. Read one file to another and use "! Feof (fp) "is used to determine whether the file is over, regardless of the type of the original file

But the size of the new file is one byte larger than that of the original file.
Q: How can I determine the end of a file correctly in C ??

Exploration
Test 1: I wrote a function to test the EOF to determine the end of the file:
-------In.txt content ---------
Abcde
-------In.txt ended -------------
------- Test1.c ----------------
Int main (int argc, char * argv []) {
Char ch;
FILE * in;
FILE * out;
   
In = fopen ("in.txt", "rb");/* in.txt is a full English character */
Out = fopen ("out.txt", "wb ");
While (ch = getc (in ))! = EOF ){
Putc (ch, out );
    }
}
The result is that the size of out.txtis exactly the same as that of in.txt.
After that, modify in.txt as follows and add some Chinese characters based on the original one:
-------In.txt the modified content is as follows ---------
Abcde
This is a test file
Test Chinese characters
-------In.txt ended --------------------
After running, remember that the size is the same. Set "in = fopen (" in.txt "," rb "); out =

Fopen ("out.txt", "w"); "to" in = fopen ("in.rar", "rb"); out = fopen ("out.rar ",

"Wb" contains many characters, in which, in.raris a compressed package file with more than 4 MB size. After running the program, out.rar is obtained.

The package is more than 800 KB. An error occurs when you double-click the package to decompress the package.

Conclusion 1: In C, if the file is opened in the form of "r" or "w",

That is to say, if the characters in the memory are read between 0 and,-1 is not possible. Therefore, it can be determined by EOF,

If it is opened in the "rb" or "wb" mode, it is possible to read the memory in binary format or write the file into a negative number,

Therefore, you can use EOF to determine that the file cannot be read. Why is there any Chinese in.txt file?

The error occurs because the Chinese text in this document does not have a binary code. The 1-1 code is in the subsequent .rar test,

When I read more than 800 K, I encountered-1, so the file ended.

Test 2: Change test1.c to test2.c.
------- Test2.c ----------------
Int main (int argc, char * argv []) {
FILE * in;
FILE * out;
   
In = fopen ("in.txt", "rb ");
Out = fopen ("out.txt", "wb ");
While (! Feof (in )){
Putc (getc (in), out );
    }
}
No matter how the file is opened or opened, the original file can be fully read into the new file, but at the end of the new file

There is a strange character at the end (two more points above y, and its binary value is-1 ).
When reading the in.rars, I should turn the cycle into a permanent cycle. After the execution, I use ctrw.z.pdf, and the size of out.rar is 11 M.

Solution

The size of the compressed file is the same. Use utraleditto open out.rar and find all

Both are 'ff' (I .e., 1-hour). The bigger part of out.rarthan in.rar is actually-1.

Conclusion 2: In C,-1 is defined as a file terminator, so the excess-1 at the end of the file will not affect the use of the file.

.

Test 3. According to the second conclusion, I think if the first character is read to-1 (the end of the file),

What will happen? I did another test,
------- Test3.c ----------------
Int main (int argc, char * argv []) {
Char ch =-1;
FILE * in;
    
In = fopen ("in.txt", "wb ");
Putc (ch, in );
}
Then, use the notepad to open in.txt. In that strange character (two more points above y, its binary value is-1),

Some English characters have been added. Test1.c and test2.c are used for the test respectively. The new files in test1 have no content; test2

All can be read to the new file, but the new file in test2 still contains the strange character (two more points above y,

Its binary value is-1 ). It's strange that if-1 is the file terminator, you should read the first character

After stopping, how can I read all the characters after-1 into the new file? After reading the information, I guess the conclusion is as follows:

: Although-1 is defined as an EOF in C, it does not mean that if-1 appears in the file, it indicates the end of the file.

In fact,-1 at the end of the file is a value returned by the system at the end of the file, instead of reading-1

You will know the end of the file (I do not know whether the description is clear). Simply put, the system now knows that the file has ended.

-1 is returned, instead of reading-1 to know the end of the file. Therefore, the-1 in the file does not mean the end of the file.

The-1 value returned by the system only indicates the end of the file when the real file pointer points to the end of the file. In

Test1 cannot be read because EOF =-1. The read-1 and EOF must be true. (This part is hard to describe.

You can try it out. If you have any questions, please discuss them .)

Fourth, use the fread () function to determine the end of the file:
------- Test4.c ----------------
Int main (int argc, char * argv []) {
Char ch;
FILE * in;
FILE * out;
   
In = fopen ("in.txt", "rb ");
Out = fopen ("out.txt", "wb ");
While (fread (& ch, sizeof (char), 1, in) = 1 ){
Putc (ch, out );
    }
}

Now let's look at the examples of c-language file read/write operations.

C ++ file stream:
Fstream // File Stream
Ifstream // input file stream
Ofstream // output file stream
// Create a text file and write information
// Output the information to the file in the same way as the output information on the screen.
# Include <iomanip. h>
# Include <fstream. h>
Void main ()
{
Ofstream f1 ("d: me.txt"); // open the file for writing. If the file does not exist

Create it.
If (! F1) return; // stops running if the file fails to be opened.
F1 <setw (20) <"name:" <"Lian Dongfang" <endl; // use the insert operator to write file content
F1 <setw (20) <"home address:" <"Henan Zhengzhou" <endl;
F1.close (); // close the file
}
Open the file d: me.txt after running. The content is as follows:
Name: lian Dongfang
Home Address: Zhengzhou, Henan province
File operations:
Open a file
File name
Note that the slash in the path name must be double-written, for example:
"D: MyFilesReadMe.txt"
File opening option:
Ios: in = 0 × 01, // for reading. If the file does not exist, create it (ifstream is enabled by default)
Ios: out = 0 × 02, // for writing. If the file does not exist, it is created. If the file already exists, the original content is cleared.

(Default open mode of ofstream)
Ios: ate = 0 × 04, // when the file is opened, the pointer is at the end of the file. The position of the pointer can be changed,

Out combination
Ios: app = 0 × 08, // for writing. If the file does not exist, it is created. If the file already exists, it is written after the original file content.

Add the new content, and the pointer is always at the end.
Ios: trunc = 0 × 10, // cut the file length to 0 (default) before reading and writing)
Ios: nocreate = 0 × 20, // an error occurs when the file does not exist. It is often used together with in or app.
Ios: noreplace = 0 × 40, // an error occurs when a file exists. It is often used together with the out.
Ios: binary = 0 × 80 // binary format file
File protection option:
Filebuf: openprot; // Default compatible sharing mode
Filebuf: sh_none; // exclusive, not shared
Filebuf: sh_read; // read sharing
Filebuf: sh_write; // write sharing
How to open a file
Specify the file name and open mode when calling the constructor.
Ifstream f ("d: 12.txt", ios: nocreate); // the default format is ios: in.

Open the file. The operation fails if the file does not exist.
Ofstream f ("d: 12.txt"); // The default value is ios: out.

Open a file
Fstream f ("d: 12. dat", ios: in | ios: out | ios: binary); // enable binary in read/write mode

File
Use Open member functions
Fstream f;
F. open ("d: 12.txt", ios: out); // use the same object

The open function is used for operations.
Check whether it is enabled successfully
Successful:
If (f ){...} // Available for ifstream and ofstream objects, and unavailable for fstream objects.
If (f. good ()){...}
Failed:
If (! F ){...} //! The operator has been overloaded.
If (f. fail ()){...}
Read/write operations
Use the <,> operator
Only read/write operations on text files can be performed. Errors may occur when binary files are used.
Use function members such as get, put, read, and write
The common function used with read is gcount (), which is used to obtain the actual number of bytes read.
Precautions for reading and writing binary files
Ios: binary must be specified in the open mode; otherwise, an error occurs during read/write operations.
You can use readwrite to perform read and write operations without using the insert or extract operators. Otherwise, an error occurs.
Use the eof () function to check whether the file has been read. Use gcount () to obtain the actual number of bytes read.
Close File
Use the member function close, for example:
F. close ();
Using destructor
When the end of the object life cycle, the system checks whether the object is closed and closes the file that is not closed.
Random file read/write
By moving the file read/write pointer, you can read and write the object at the specified position.
Seekg (absolute position); // absolute movement, // input stream operation
Seekg (relative position, reference position); // relative operation
Tellg (); // returns the current pointer position
Seekp (absolute position); // absolute movement, // output stream operation
Seekp (relative position, reference position); // relative operation
Tellp (); // returns the current pointer position
Reference location:
Ios: beg = 0 // relative to the file header
Ios: cur = 1 // relative to the current location
Ios: end = 2 // relative to the end of the file
Example of reading/writing a text file
// To correctly read the data written into the file, it is best to separate the data
# Include <fstream. h>
Void main ()
{
Fstream f ("d: try.txt", ios: out );
F <1234 <''<3.14 <'A' <" How are you "; // write data
F. close ();
F. open ("d: try.txt", ios: in );
Int I;
Double d;
Char c;
Char s [20];
F> I> d> c; // read data
F. getline (s, 20 );
Cout <I <endl; // Display Data
Cout <d <endl;
Cout <c <endl;
Cout <s <endl;
F. close ();
}
Running result:
1234
3.14
A
How are you
Press any key to continue
Display text file content
// Use get () to read a character at a time ----------- solution 1
# Include <fstream. h>
Void main ()
{
Ifstream fin ("d: .txt", ios: nocreate );
If (! Fin ){
Cout <"File open error! N ";
Return;
}
Char c;
While (c = fin. get ())! = EOF) cout <c; // pay attention to the judgment of the end condition
Fin. close ();
}
// Use get (char *, int n, char delim = 'n') to read multiple characters at a time-solution 2
// Use the features of '& prime; not included in the text file to read
# Include <fstream. h>
Void main ()
{
Ifstream fin ("d: .txt", ios: nocreate );
If (! Fin ){
Cout <"File open error! N ";
Return;
}
Char c [80];
While (fin. get (c, 80, '& prime ;)! = NULL) cout <c; // pay attention to the judgment of the end condition
Fin. close ();
}
// Use read (char *, int n) to read the file --------- solution 3
# Include <fstream. h>
Void main ()
{
Ifstream fin ("d: .txt", ios: nocreate );
If (! Fin ){
Cout <"File open error! N ";
Return;
}
Char c [80];
While (! Fin. eof () // determines whether the file has been read.
{
Fin. read (c, 80 );
Cout. write (c, fin. gcount ());
}
Fin. close ();
}
Copy an object
// Binary file operation example
# Include <fstream. h>
Void main ()
{
Ifstream fin ("C: 1.exe", ios: nocreate | ios: binary );
If (! Fin ){
Cout <"File open error! N ";
Return;
}
Ofstream fout ("C: 2.exe", ios: binary );
Char c [1024];
While (! Fin. eof ())
{
Fin. read (c, 1024 );
Fout. write (c, fin. gcount ());
}
Fin. close ();
Fout. close ();
Cout <"Copy over! N ";
}

 

Related Article

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.