程序设计语言

c++文件内容编辑及append,不清空原内容

2010年8月28日 阅读(691)

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;

int main (int argc, char *argv[])
{
    char logItemBuffer[129];
    int lineLen = 128;
    memset(logItemBuffer,’#’,lineLen);
    logItemBuffer[129] = ‘\0’;
    //write meta info
    string logMetaInfo = "LOG_META_TAG:ItemTypeNum:JobName:TaskName:InstanceID:StartTime—:";
    strncpy(logItemBuffer,logMetaInfo.c_str(),logMetaInfo.size());
    fstream fout("test.txt",ios::in|ios::out);
    if ( !fout.is_open() ) {
          return 0;
     }

    fout << logItemBuffer << endl;
   
    cout << fout.tellp() << endl;
    int logOffSet =  fout.tellp();
   
    memset(logItemBuffer,’#’,lineLen);
    logItemBuffer[129] = ‘\0’;
    string logItemStr = "LOG_ITEM_TAG:test_name:test_value:test_time—:"; 
    strncpy(logItemBuffer,logItemStr.c_str(),logItemStr.size());
    fout << logItemBuffer << endl;
    cout << fout.tellp() << endl;
   
    //rewrite log
    fout.seekp(logOffSet);    
    memset(logItemBuffer,’#’,lineLen);
    logItemBuffer[129] = ‘\0’;
    string logItemCurrentStr = "LOG_ITEM_TAG:name:value:time:"; 
    strncpy(logItemBuffer,logItemCurrentStr.c_str(),logItemCurrentStr.size());
    fout << logItemBuffer << endl;   
   
    //append log
    fout.seekp(0,ios::end); 
    logItemCurrentStr = "LOG_ITEM_TAG:name:value:time:";  
    fout << logItemCurrentStr << endl;   
   
    fout.close();
   
    ofstream t("test.txt",ios::in|ios::out);//if only ios::out is used,the file content will be cleared.
    t.close();
   
    getchar();
    return 0;
}

You Might Also Like