无法读取/打开.dat文件

时间:2013-11-09 09:16:08

标签: c++

在阅读.dat文件时需要帮助,我无法打开文件

该程序用于空气质量指数检测器,AQI机器每分钟记录颗粒浓度并将其保存到每天的新数据文件中。所以我需要让这个程序每分钟运行一次并将浓度转换成AQI读数。

文件名的格式为“ES642_2013-11-09.dat”,其中ES642是机器的软件名称,其余为年,月和日。

此处的代码仅供文件阅读部分使用:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, const char * argv[]) {
for(;;){
    time_t now = time(0);
    if(now % 60 == 0) {     //running the program every minute
    //if(now % 1 == 0) {    //running the program every second
        tm *ltm = localtime(&now);

        int year_int = 1900+ltm->tm_year;   //defining the current year
        int month_int = 1+ltm->tm_mon;      //defining the current month
        int day_int = ltm->tm_mday;         //defining the curret day

        string year = to_string(year_int);     // saving them as a string
        string month = to_string(month_int);
        string day = to_string(day_int);

        if(month.length() == 1) {
            month = "0" + month;
        }                               //since the software saves 9 as 09 in the file name, therefore modiying the month.

         if(day.length() == 1) {
            day = "0" + day;
        }                               //since the software saves 9 as 09 in the file name, therefore modiying the day.
         cout<<year<<"\t"<<month<<"\t"<<day<<endl;


        const string filename = "ES642_" + year + "-" + month + "-" + day + ".dat";

        /* for reading today's file, the filename should be

         const string filename = "ES642_2013-11-09.dat";

         but as there is a new data file for each day, therefore i'm using variables for each filename instead of constants

         const string filename = "ES642_" + year + "-" + month + "-" + day + ".dat";

         */


        string line;
        ifstream myfile;
        myfile.open(filename,ios::binary);
         if (myfile.is_open()) {
            while ( getline (myfile,line) )
            {
                cout << line << endl;
            }
            myfile.close(); }
         else {
            cout << "Unable to open file" << endl;
         }
    }
}
  return 0;
}

0 个答案:

没有答案