Find content in the file stream with std :: find

xiaoxiao2021-04-08  291

Find content in the file stream with std :: find MYTHMA

In general, I rarely use iteratory istream_iterator. Recently, when writing a function of reading a specific format file, find the use of iStream_Iterator and std :: Find can be very convenient to implement the file content.

Note: All of the following assumes that the text file, the binary is not tested.

Assume that something to find is a String in a file, which can be implemented:

IFStream Fin

"

Yourfile

"

);

IF

(FIN)

{Istream_iterator strReader (fIn); // file begin istream_iterator strEOF; // file end string strToFind = "mythma"; strReader = find (strReader, strEOF, strToFind); while (! StrReader = strEOF) { strreader; // do something // * strreader; // dereference to get current string // Find next strreader = find (strreader, streof, strup);}}

As can be seen from the code above, the FIN can be seen as a container that stores const string.

Exterior:

1. When can I consider using ISTREAM_ITERATOR?

I think that when the file is the same data, ISTREAM_ITERATOR can be easily read and find an object.

1) If the content in the file is the same basic type of data, such as int, you can use iStream_iterator:

iStream_iterator

<

int

>

Intreader (FIN);

//

FILE BEGIN

iStream_iterator

<

int

>

Inteof;

//

File end

2) If it is stored in the data order of a custom CUSER object, you need to overload Operator >>, then use this:

iStream_iterator

<

CUSER

>

Intreader (FIN);

//

FILE BEGIN

iStream_iterator

<

CUSER

>

Inteof;

//

File end

If you need to find objects, you also need to overload comparison operators in a specific case.

2. Processing in the file is the processing of heterogeneous data. First, all content in the file can be used to operate with String, which does not need to be discussed. What happens when reading a file containing non-int data with iStream_Iterator ? After testing, when ISTREAM_ITERATOR encountered the first non-int data, iterative terminates. --- Test code:

Using

Namespace

IFSTREAM FIN

"

Test.txt

"

);

IF

(FIN)

{ISTREAM_ITERATOR Intreader (FIN); istream_iterator InteoF; Copy (intReader, inteof, ostream_iterator (cout, "));}

--- Test file Test.txt: 1 22 3.4 Haha 44 Hello --- Output: 1 22 33, Efficiency ISTREAM_ITERATOR In addition to making the code looks relatively simple, everyone is most concerned about the efficiency problem. I have not tested compared.

转载请注明原文地址:https://www.9cbs.com/read-132709.html

New Post(0)