码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-10-24 12:54:51      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:io   os   ar   sp   on   amp   ad   bs   ef   

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 should 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 should 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!

标签:io   os   ar   sp   on   amp   ad   bs   ef   

原文地址:http://www.cnblogs.com/airwindow/p/4047855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!