zoukankan      html  css  js  c++  java
  • a trick in reading and storing file in the exact way!

    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 ' ' as delimiter).

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

    However, in this way we can add extra ' ' 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 ' ' 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 ' ' at the last line of reading file, we can avoid this by defering the time of add ' ' by using pre_line and buffer_line.

    only this is a new line available(buffer_line), we append the ' ' character to the pre_line. Otherwise, it is the lat line, we should write it directly into the outstream without appeding the ' ' 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 += ' ';  /*pre_line + ' ' 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 ' '*/

                break;

            }

    }

        

      out.close();

  • 相关阅读:
    Eclipse 中生成帮助文档 (javadoc) 迎客
    网管利器:七大免费网络工具 迎客
    oracle 11g 学习笔记 10_27
    oracle 11g 学习笔记 10_29
    oracle 11g学习笔记 2012_10_22
    oracle 11g 学习笔记 2012_10_25(2)
    oracle 11g 学习笔记 10_26
    oracle 11g 学习笔记 2012_10_24(1)
    oracle 11g 学习笔记2012_10_23(2)
    oracle 11g 学习笔记 2012_10_25(a)
  • 原文地址:https://www.cnblogs.com/airwindow/p/4047855.html
Copyright © 2011-2022 走看看