Input/output description

Source: Internet
Author: User

In this chapter, I will mention some useful functions. I will show you how to open a file that can be read and written at the same time. In addition, I will introduce you to other methods to open the file and how to determine whether the open operation is successful. Therefore, please continue reading!

So far, what I have shown you is a single way to open a file: either open for reading or open for writing. However, files can be opened in other ways. So far, you should have understood the following methods:

 

Ifstream openfile(“cpp-home.txt ");

 

Oh, this is not the only method! As mentioned previously, the above Code creates an ifstream-like object and passes the object name to its constructor. But in fact, there are still many overloaded constructors that can accept more than one parameter. At the same time, there is also an open () function that can do the same thing. The following is an example of the above Code, but it uses the open () function:

 

Ifstream openfile;

Openfile.open(“cpp-home.txt ");

 

Are there any differences between them? Oh, I did a lot of tests and the conclusion is that there is no difference! However, if you want to create a file handle but do not want to specify a file name immediately, you can use the open () function to specify it later. By the way, an example of using the open () function is provided: if you open a file, close it, and attempt to open another file with the same file handle, you will need to use the open () function.

Consider the following code example:

 

# Include <fstream. h>

 

Void read (ifstream & T) // pass the file stream to the Function

{

// The method to read a file, that I showed you before

Char ch;

 

While (! T. EOF ())

{

T. Get (CH );

Cout <ch;

}

 

Cout <Endl <"--------" <Endl;

}

 

Void main ()

{

Ifstream T ("file1.txt ");

Read (t );

T. Close ();

 

T. Open ("file2.txt ");

Read (t );

T. Close ();

}

 

For this reason, you only need file1.txtand file2.txt and store the text content. You will see the content.

The file name is not the only parameter that you can pass to the open () function or constructor (actually the same. The following is a function prototype:

 

Ifstream openfile (char * filename, int open_mode );

 

You should know that filename represents the name of the file (a string), while open_mode (open mode) appears ). The value of open_mode is used to define how to open a file. The following is a list of open modes:

Name
Description

IOS: In
Open a readable File

IOS: Out
Open a writable file

IOS: app
All data you write will be appended to the end of the file. This method uses IOs: Out

IOS: ATE
All data you write will be appended to the end of the file. This method does not use IOs: Out

IOS: Trunk
Delete existing file content (clear file)

IOS: nocreate
If the file to be opened does not exist, you cannot call the open () function using this parameter.

IOS: noreplace
If the file to be opened already exists, an error is returned when you try to open it using the open () function.

IOS: Binary
Open a file in binary format.

 

In fact, the above values belong to an int constant of the enumeration type. But to make your programming career less painful, you can use those names as shown in the table above.

The following is an example of how to use the open mode:

 

# Include <fstream. h>

 

Void main ()

{

Ofstream SaveFile ("file1.txt", IOS: ATE );

 

SaveFile <"that's new! /N ";

 

SaveFile. Close ();

}

 

As you can see in the table, Using IOS: ate will write data from the end of the file. If I do not use it, the original file content will be overwritten by the re-written content. However, since I have used it, I will only add it at the end of the original file. Therefore, if the original content of file1.txt is as follows:

Hi! This is test from www.cpp-home.com!

After the above code is executed, the program will add "that's new!" to it !", So it looks like this:

Hi! This is test from www.cpp-home.com! That's new!

If you want to set more than one open mode flag, you only need to use the OR operator or |, like this:

 

IOS: ate | IOs: Binary

 

I hope now you understand what "open mode" means!

Now, it's time to show you something really useful! I bet you still don't know how to open a file that can be read and written at the same time! The following is the implementation method:

 

Fstream file(“cpp-home.txt ", IOS: In | IOs: Out );

 

In fact, this is just a declaration statement. I will give you a sample code after the following lines. But now I want to mention something you should know first.

The above Code creates a stream file handle named "File. As you know, it is an object of the fstream class. When using fstream, you should specify IOs: In and IOs: out as the file opening mode. In this way, you can read and write files at the same time without creating a new file handle. Oh, of course, you can only perform read or write operations. In that case, you should use only IOs: In or only IOs: Out. The question to be considered is: if you plan to do this, why don't you use ifstream and ofstream separately?

The following shows the sample code:

 

# Include <fstream. h>

 

Void main ()
{

Fstream file ("test.txt", IOS: In | IOs: Out );

 

File <"Hi! "; // Set" Hi !" Write files

Static char STR [10]; // when static is used, the array is automatically initialized.

// It is cleared to zero

 

File. seekg (IOs: Beg); // return to the file header.

// This function will be explained later

File> STR;

Cout <STR <Endl;

 

File. Close ();
}

 

Okay, there are some new things here, so I will explain them one by one:

 

Fstream file(‑test.txt ", IOS: In | IOs: Out); -- this row creates an fstream object. When executed, the test.txt file is opened in the read/write format. This means that you can read files and write data at the same time.

 

File <"Hi !"; -- I bet you already know what it means.

 

Static char STR [10]; -- this creates an array of 10 characters. I guess static is strange to you. If so, ignore it. This only initializes the array while creating it.

 

File. seekg (IOs: Beg); -- OK, I want you to understand what it will do, so I will start my explanation with something a little digress but important.

Remember it:

 

While (! Openfile. EOF ())

{

Openfile. Get (CH );

Cout <ch;

}

 

Have you ever wondered what operations are actually performed behind the scenes? Whether it is or not, I will explain it to you. This is a while loop, which will be repeated until program operations reach the end of the file. But how does this loop know whether it has reached the end of the file? Well, when you read a file, there will be something similar to "Inside-pointer", which indicates where you have read (written as well) the file, just like the cursor in notepad. Whenever you call openfile. Get (CH), it returns the character at the current position, stores it in the CH variable, and moves this built-in pointer one character forward. So the next time the function is called, it will return the next character. This process will be repeated until the reading reaches the end of the file. So let's go back to the line of code: the function seekg () will position the built-in pointer to the specified position (depending on your decision ). You can use:

 

IOS: beg -- you can move it to the first end of a file.

IOS: end -- you can move it to the end of a file.

 

Alternatively, you can set the number of characters to jump forward or backward. For example, if you want to locate the current position before 5 characters, you should write:

File. seekg (-5 );

If you want to skip 40 characters, you should write:

File. seekg (40 );

At the same time, I must point out that the seekg () function is overloaded and can contain two parameters. Another version is like this:

File. seekg (-5, IOS: End );

In this example, you can read the last four characters of the file text, because:

1) You first reached the end (IOs: end)

2) Then you reach the position of the first five characters at the end (-5)

Why do you read 4 characters instead of 5 characters? Oh, you only need to regard the last one as "lost", because the "things" at the end of the file is neither a character nor a blank character, it is just a location :: the end parameter is beyond the scope of the file. Specifically, it is the next position pointing to the last character of the file, similar to the end iteration point of each container in STL, the end iteration point points to the next position of the last element. This design may facilitate traversal in a loop ).

You may want to know why I want to use this function. Er, after I write "hi" into the file, the built-in pointer will be set to point to the back of it ...... That is, the end of the file. Therefore, I must set the built-in pointer back to the starting position of the file. This is the exact purpose of this function.

File> STR; -- this is new! Oh, I'm sure this line of code reminds you of CIN>. Actually, they are quite correlated. This row reads a word from the file and saves it to the specified array variable.

For example, if the file contains such text snippets:

Hi! Do you know me?

If File> STR is used, only "Hi !" Output to the STR array. You should have noticed that it actually reads spaces as word separators.

Since only one "Hi!" exists in the file !", I don't need to write a while loop. It will take more time to write code. This is why I use this method. By the way, In the while loop of reading files that I have used so far, the program reads files by a single character. However, you can also read a word, such:

 

Char STR [30]; // each word cannot exceed 30 characters

While (! Openfile. EOF ())

{

Openfile> STR;

Cout <STR;

}

 

You can also read data in one row, as shown in the following code:

 

Char line [100]; // each row is stored here
While (! Openfile. EOF ())
{

Openfile. Getline (line, 100); // 100 is the size of the array.

Cout <line <Endl;
}

 

You may want to know which method to use. Well, I suggest you use the row-by-row reading method, or the character-by-character reading method I mentioned at first. The word-to-word reading method is not a good solution, because it does not read the information of a new row, so if you create a new row in your file, it will not display those contents in a new line, but add them after the printed text. The use of Getline () or get () will show you the true nature of the file!

Now, I will show you how to check whether the file opening operation is successful. In terms of implementation, there are few good methods, and I will cover them all. Note that when "X" appears, it can actually be replaced by "O" and "I, or it can be nothing (it will be a fstream object ).

Example 1: The most common practice

 

Xfstream file(“cpp-home.txt ");

If (! File)
{

Cout <"error opening the file! Aborting... /N ";

Exit (1 );
}

 

 

Example 2: If the file has been created, an error is returned.

 

Ofstream file ("unexisting.txt", IOS: nocreate );

 

If (! File)

{

Cout <"error opening the file! Aborting... /N ";

Exit (1 );

}

 

Example 3: Use the fail () function

 

Ofstream file ("filer.txt", IOS: nocreate );

 

If (file. Fail ())

{

Cout <"error opening the file! Aborting... /N ";

Exit (1 );

}

 

The new thing in Example 3 is the fail () function. If any input/output error occurs (not at the end of the file), it returns a non-zero value.

I also want to talk about something that I think is very important! For example, if you have created a stream file object, but you have not opened the file, like this:

 

Ifstream file; // it can also be an ofstream

 

In this way, we have a file handle, but we still haven't opened the file. If you want to open it later, you can use the open () function. I have introduced it in this tutorial. However, if somewhere in your program, you may need to know whether the current handle is associated with an opened file, you can use is_open () for detection. If the file is not opened, it returns 0 (false); if the file has been opened, it returns 1 (true ). For example:

 

Ofstream file1;

File1.open ("file1.txt ");

Cout <file1.is _ open () <Endl;

 

The above code will return 1 (: file1.is _ open () function, which is the same as the following sentence), because we have opened a file (in the second line ). The following code returns 0, because we didn't open the file, but created a stream file handle:

Ofstream file1;

Cout <file1.is _ open () <Endl;

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.