初学c++,菜鸟一个,项目需要在Linux下学习文件io操作流,主要是写日志文件和读取参数配置文件,查找了别人的一些方法,选用简单易懂的,记录下来。
//获取系统时间 标准格式
string GetSystemTime()
{
time_t tNowTime;
time(&tNowTime);
tm *tLocalTime = localtime(&tNowTime);
char szTime[30] = {'\0'};
strftime(szTime,30,"[%Y-%m-%d %H:%M:%S] ",tLocalTime);
string strTime = szTime;
return strTime;
}
//键值对方式读取参数配置文件
bool readConfigFile(const char* cfgfilepath,const string & key, string & value1)
{
fstream cfgFile;
cfgFile.open(cfgfilepath);//打开文件
if(!cfgFile.is_open())
{
cout<<"can not open cfg file!"<<endl;
return false;
}
char tmp[100];
while(!cfgFile.eof())//循环读取每一行
{
cfgFile.getline(tmp,100);//每行读取前100个字符,100个应该足够了
string line(tmp);
size_t pos = line.find('=');//找到每行的“=”号位置,之前是key之后是value
if(pos==string::npos)
return false;
string tmpKey = line.substr(0,pos);//取=号之前
if(key==tmpKey)
{
value1 = line.substr(pos+1);//取=号之后
return true;
}
}
cfgFile.close();
return false;
}
int main(int argc, char **argv)
{
ofstream fout("log.txt",ios::app);//追加文本方式,不使用ios::app为覆盖
fout <<GetSystemTime()<<"start..."<< endl;
fout.close();
const char* cfgfilepath="config.cfg";
const string key_X="X";
string value_X="";
float X=0;
readConfigFile(cfgfilepath,key_X,value_X);
X=atof(value_X.c_str());//string转float
return 0;
}