writeDDTime.cpp 2.22 KB
/////////////////
/// CPP HEADER //
/////////////////
#include <iostream>
#include <string>
#include <fstream>
#include <vector>

///////////////
/// C HEADER //
///////////////
#include <stdlib.h> 

////////////////////
/// NETCDF HEADER //
////////////////////
#include <netcdf.h>

using namespace std;

int main(int argc, char const *argv[])
{
	if (argc != 2)
	{
		cerr << "[ERROR] Usage : ./writeDDTime (nc_file)";
		exit(EXIT_FAILURE);
	}

	string filename = "ddTime.txt";
	vector<string> ddTime; 
	ifstream myFile(filename.c_str(), ios::in);

	if(myFile)
	{
    	string line;
        while(getline(myFile, line))
        {
            ddTime.push_back(line);
        }

        myFile.close();
	}
	else {
		cerr << "[ERROR] Enable to open " << filename << endl;
		exit(EXIT_FAILURE);
	}

	// OPEN NC
	string ncFile = argv[1];
	int ncid;
	// nc_open(ncFile.c_str(), NC_WRITE, &ncid);
	nc_create(ncFile.c_str(), NC_CLOBBER, &ncid);

	// DEFINITION MODE
	// nc_redef(ncid);
	int timelength_dimid;
	int time_dimid;
	// nc_inq_dimid(ncid, "Time", &time_dimid);
	nc_def_dim(ncid, "Time", NC_UNLIMITED, &time_dimid);
	nc_def_dim(ncid, "TimeLength", 17, &timelength_dimid);
	
	// int dataId;
	int time_tab_dimid[2];
	// int data_tab_dimid[2];
	int time_varid;
	time_tab_dimid[0] = time_dimid;
	time_tab_dimid[1] = timelength_dimid;
  	// data_tab_dimid[0] = time_dimid;
  	// data_tab_dimid[1] = dataId;

  	nc_def_var(ncid, "Time", NC_CHAR, 2, time_tab_dimid, &time_varid);
  	
  	int startTime_varid, stopTime_varid;
  	nc_def_var(ncid, "StartTime", NC_CHAR, 1, &timelength_dimid, &startTime_varid);	
	nc_def_var(ncid, "StopTime", NC_CHAR, 1, &timelength_dimid, &stopTime_varid);
	
	nc_enddef(ncid);

  	// WRITING MODE
	size_t start[2], timeCount[2];
	// size_t dataCount[2];
  	size_t off;

	timeCount[0] = 1;
	timeCount[1] = 17;
	// dataCount[0] = 1;
	// dataCount[1] = 3;
	start[1] = 0;
	off = 0;
	
	int ddSize = ddTime.size();
	for (int i = 0; i < ddSize; i++)
    {
    	start[0] = off;		
		nc_put_vara_text(ncid, time_varid, start, timeCount, ddTime[i].c_str());
		off++;
    }

    nc_put_var_text(ncid, startTime_varid, ddTime[0].c_str());
	nc_put_var_text(ncid, stopTime_varid, ddTime[ ddSize-1 ].c_str());

    // Close the file
	nc_close(ncid);

	return 0;
}