A trick in reading and storing file in the exact way!

Source: Internet
Author: User

Read and Write File is a very common operation regarding file mainuplation.

However, the powerfull Getline only can read line by line (with new line character '\ n' as delimiter ).

Inorder to write the line back into file, we often have to add' \ n' at the last of each line.

However, in this way we can add extra '\ n' character compared to the original file.

To avoid this inaccuracy, may be not a big deal in a common situation, but I have tested that an extra '\ n' at *. tgz file can infere the untar of it.

I suggest the following way To Read and Write File in exact way, without adding any extra character.

The key idea:

Since we shoshould not add' \ n' at the last line of reading file, we can avoid this by defering the time of add' \ n' by using pre_line and buffer_line.

Only this is a new line available (buffer_line), We append the '\ n' character to the pre_line. otherwise, it is the lat line, we shoshould write it directly into the outstream without appeding the '\ n' character.

Coding sample:

 

Ofstream out;

Out. Open (obj_path.c_str ());

String pre_line;

String buffer_line;

Getline (CIN, pre_line );

While (1 ){

If (Getline (CIN, buffer_line )){

Pre_line + = '\ n';/* pre_line +' \ n' if its next line is not the last line */

Out <pre_line;

Pre_line = buffer_line;

} Else {

Out <pre_line;/* The pre_line is the last new, no need to add' \ n '*/

Break;

}

}

Out. Close ();

 

A trick in reading and storing file in the exact way!

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.