C++标准库获取时间、简单的文件操作

来源:互联网 发布:阿里云os系统官网 编辑:程序博客网 时间:2024/05/24 04:45

参考文章:

http://blog.csdn.net/luotuo44/article/details/46854229

http://www.2cto.com/kf/201404/290706.html

http://www.cplusplus.com/reference/iomanip/put_time/

http://blog.csdn.net/u010177286/article/details/50353464

http://blog.csdn.net/wangjieest/article/details/7761051

http://codereview.stackexchange.com/questions/124395/c-time-types-and-format-conversions   这个借鉴的是put_time()转string

只是在以上的一堆,借鉴了一个简单的用C++标准库的日期及其格式化程序。

程序如下:(QT下面写的)

#include <chrono>#include <ctime>#include <string>#include <iomanip>#include <iostream>#include <fstream>#include <sstream>using namespace std::chrono;using namespace std;int main(int argc, char *argv[]){    system_clock::time_point now = system_clock::now();    std::time_t time = system_clock::to_time_t(now);    std::stringstream ss;   //把时间数据格式转换为字符串    ss<<std::put_time(std::localtime(&time),"%Y-%m-%d %H:%M:%S ");    cout<<ss.str()<<endl;    ofstream wfile("data-"+ss.str()+".txt");    if(wfile.is_open()){        wfile<<"hello wk!!!";   //往文件中写数据        cout << "file open successed.";    }    else       cout<<"file open failed!";        // auto t = chrono::system_clock::to_time_t(std::chrono::system_clock::now());        // cout<< std::put_time(std::localtime(&t), "%Y-%m-%d %X")<<endl;        // cout<< std::put_time(std::localtime(&t), "%Y-%m-%d %H.%M.%S")<<endl;        return 0;    }


但是,会报错,put_time()不是标准库中的函数,同样的还有get_time().

查阅资料显示,put_time()、get_time()在gcc5中才实现,gcc4中没有,

而ubuntu14.04默认安装的是gcc4.8,太老了:http://stackoverflow.com/questions/14136833/stdput-time-implementation-status-in-gcc

安装gcc5,并设置,参照http://blog.sina.com.cn/s/blog_54dd80920102vvt6.html


错误:

 ofstream data_file("datarecord-"+ss.str()+".txt");

。。。。。。。。。has initializer but incomplete type

原因:没有包含操作文件的头文件#include<fstream>

0 0