【发布时间】:2018-01-04 00:27:11
【问题描述】:
这是我的第一个问题:
我正在尝试从 NetCDF 文件中读取“全局属性”(使用 C++ 旧版 API)。 “全局属性”是指添加到 NcFile 而非 NcVar 的属性。
对于大多数事情,“Example netCDF programs”很有用——但没有“全局属性”的示例。
查阅“netcdfcpp.h”我发现了一些东西:
- NcFile 有一个成员函数:
NcAtt* get_att(NcToken) const; - NcAtt 没有公共构造函数
- NcAtt 是 NcFile 的好友:
friend class NcFile; - NcAtt 有一个私有构造函数:
NcAtt( NcFile*, NcToken); - NcAtt 有一个公共成员函数
NcValues* values( void ) const; - NcValues 有一个通过
ncvalues.h标头定义的 API
我的编码技能不足以理解我如何在 NcFile 的 NcAtt 类中返回存储为 NcValue 的 string/int/float。
附件是我的问题“NetCDF_test.cpp”的示例代码,在“LoadNetCDF”函数的实现中缺少关键部分。
代码编译成功:(编辑:另外,“TestFile.nc”被正确创建)
g++ -c NetCDF_test.cpp -o NetCDF_test.o
g++ -o NCTEST NetCDF_test.o -lnetcdf_c++ -lnetcdf
示例代码:
#include <iostream> // provides screen output (i.e. std::cout<<)
#include <netcdfcpp.h>
struct MyStructure {
std::string MyString;
int MyInt;
float MyFloat;
MyStructure(); // default constructor
int SaveNetCDF(std::string); // Save the struct content to "global attributes" in NetCDF
int LoadNetCDF(std::string); // Load the struct content from "global attributes" in NetCDF
};
MyStructure::MyStructure(void)
{
MyString = "TestString";
MyInt = 123;
MyFloat = 1.23;
}
int MyStructure::SaveNetCDF(std::string OUTPUT_FILENAME)
{
NcError err(NcError::silent_nonfatal);
static const int NC_ERR = 2;
NcFile NetCDF_File(OUTPUT_FILENAME.c_str(), NcFile::Replace);
if(!NetCDF_File.is_valid()) {return NC_ERR;}
if(!(NetCDF_File.add_att("MyString",MyString.c_str()))) {return NC_ERR;}
if(!(NetCDF_File.add_att("MyInt",MyInt))) {return NC_ERR;}
if(!(NetCDF_File.add_att("MyFloat",MyFloat))) {return NC_ERR;}
return 0;
}
int MyStructure::LoadNetCDF(std::string INPUT_FILENAME)
{
NcError err(NcError::silent_nonfatal);
static const int NC_ERR = 2;
NcFile NetCDF_File(INPUT_FILENAME.c_str(), NcFile::ReadOnly);
if(!NetCDF_File.is_valid()) {return NC_ERR;}
// ???? This is where I am stuck.
// How do I read the global attribute from the NetCDF_File ??
return 0;
}
int main()
{
std::cout<< "START OF TEST.\n";
MyStructure StructureInstance; // datamembers initialized by constructor
StructureInstance.SaveNetCDF("TestFile.nc");
StructureInstance.MyString = "Change string for sake of testing";
StructureInstance.MyInt = -987;
StructureInstance.MyFloat = -9.87;
StructureInstance.LoadNetCDF("TestFile.nc"); // data members are supposed to be read from file
std::cout<< "Now the data members of StructureInstance should be TestString, 123, and 1.23\n";
std::cout<< StructureInstance.MyString << " ; " << StructureInstance.MyInt << " ; " << StructureInstance.MyFloat <<"\n";
std::cout<< "END OF TEST.\n";
}
【问题讨论】: