write content to file via ofstream and read from file via ifstream

#include <iostream>
#include <uuid/uuid.h>
#include <ctime>
#include <unistd.h>
#include <string.h>
#include <ostream>
#include <fstream>
#include <sstream>

using namespace std;

static char *dtValue=(char*)malloc(20);
static char *uuidValue=(char*)malloc(40);
static int num=0;

char *getUuid3()
{
    uuid_t newUUID;
    uuid_generate(newUUID);
    uuid_unparse(newUUID,uuidValue);
    return uuidValue;
}

void printTime2()
{
    while(1)
    {
        cout<<"Now is "<<getTimeNow()<<endl;
        sleep(1);
    }
}

char *getTimeNow()
{
    time_t rawTime=time(NULL);
    struct tm tmInfo=*localtime(&rawTime);
    strftime(dtValue,20,"%Y%m%d%H%M%S",&tmInfo);
    return dtValue;
}

Write content to file physically via ofstream

void writeFile5()
{
    ofstream wFile("log.txt",ios::app|ios::out);
    if(!wFile.is_open())
    {
        cout<<"Create or open log.txt failed!"<<endl;
        return;
    }

    int loops=100,repeateTimes=1000000;
    stringstream ss;
    for(int i=0;i<loops;i++)
    {
        for(int j=0;j<repeateTimes;j++)
        {
            ss<<++num<<","<<getUuid3()<<endl;            
        }
        wFile<<ss.str()<<endl;
        ss=stringstream();
        cout<<"Now num="<<num<<",now is "<<getTimeNow()<<endl;
    }
    wFile.close();
    cout<<"Finished in writeFile5() and now is "<<getTimeNow()<<endl;
    free(uuidValue);
    free(dtValue);
}

 

Read content from physical file via ifstream in ios::in mode

void readFile6()
{
    ifstream rFile("log.txt",ios::app|ios::in);
    if(!rFile.is_open())
    {
        cout<<"Open log.txt failed!"<<endl;
        return;
    }

    string line;
    while(getline(rFile,line))
    {
        ++num;
        if(num%1000000==0)
        {
            cout<<"Num="<<num<<",line content="<<line<<",now is "<<getTimeNow()<<endl;
        }
    }

    rFile.close();
    cout<<"Finished in readFile6() and now is "<<getTimeNow()<<endl;
    free(uuidValue);
    free(dtValue);
}

 

上一篇:CLR via C# 基类构造函数调用继承类的override method疑问


下一篇:QSGD: Communication-Efficient SGD via Gradient Quantization and Encoding