C/C++教程

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

本文主要是介绍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);
}

 

这篇关于write content to file via ofstream and read from file via ifstream的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!