C++標準庫獲取時間、簡單的文件操作


參考文章:

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>

發佈了44 篇原創文章 · 獲贊 16 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章