How can I check that a file is a valid HDF5 file? - c++

Based on the example given here, I have a file image loaded into memory as a string with a valid handler. This was done using H5LTopen_file_image().
How can I check that a file is a valid HDF5 file?
I found only a program called H5check, which has a complicated source code. So, I'm wondering, is there a simple function with a simple return value to verify that whatever in the hid_t handler is a valid HDF5 file?

In C++:
std::string filename = "foo.h5";
if(!H5::H5File::isHdf5(filename.c_str()))
{
std::string err_msg = filename + " is not an HDF5 file.\n";
throw std::logic_error(err_msg);
}
In Python, use
import h5py
if not h5py.is_hdf5('foo.h5'):
raise ValueError('Not an hdf5 file')

Related

Check if file exists using StreamReader

I open this file to read data, but if file doesn't exist it throws error. So how can I check if file exists? In console project I can use ifstream, where I can check it by writing if(!file) {}, and StreamReader doesn't allow me to do this.
StreamReader^ data = gcnew StreamReader("data.txt");
You need to read the documentation.
The exception thrown is FileNotFoundException if the file cannot be found.

How do you stream a binary representation of a .zip folder in mfc c++?

I am trying to stream a .zip file to hardware using mfc c++. The hardware needs the file still in .zip format when sent over because it will do the unpacking itself.
I have been unable to find a class or method to grab a .zip file and stream it over.
Most searches lead me to questions about unzipping or zipping using c++ which is of no use in my particular case.
Any advice? Has anyone ran into this situation?
The following code snippet reads the 100 first bytes of a file into a buffer using CFile:
CFile f;
if (f.Open(L"path_to_your_file", CFile::modeRead))
{
char buffer[100];
f.Read(buffer, sizeof buffer);
f.Close();
}
else
{
// handle error
DWORD error = GetLastError();
// error number in error
...
}
This is more or less all you need. Google for the documentation of CFile.
You should be able to figure out the rest.
The format of the file you're reading is irrelevant. You just need to read the contents of your file and send it to the hardware.

How can I fix an `OSError: file error: bad input file` in RDkit with .sdf file?

I'm using a third party code in python from an arxiv which use RDkit as a library. It takes a .sdf file with data about chemicals molecules as an argument, but then RDkit throw an error:
OSError: File error: Bad input file file.sdf
I followed the instructions, installed all the packages needed, downloaded the files as they said, raise de swap space in my computer because the .sdf is pretty big, strike off a big part of the data of this file... but I can't make it run, none of this tries got success.
I have been looking to the RDkit package and this is the piece of code that raise the error:
LocalForwardSDMolSupplier(std::string filename, bool sanitize, bool removeHs,
bool strictParsing) {
std::istream *tmpStream = nullptr;
tmpStream = static_cast<std::istream *>(
new std::ifstream(filename.c_str(), std::ios_base::binary));
if (!tmpStream || (!(*tmpStream)) || (tmpStream->bad())) {
std::ostringstream errout;
errout << "Bad input file " << filename;
throw RDKit::BadFileException(errout.str());
}
dp_inStream = tmpStream;
df_owner = true;
df_sanitize = sanitize;
df_removeHs = removeHs;
df_strictParsing = strictParsing;
POSTCONDITION(dp_inStream, "bad instream");
}
It seems to be C++, which I don't know.
I expect to see how this code works, with which inputs and outputs, to adapt to my code. I would like to see with this .sdf file, but maybe another one could work for my purpose.
Finally, I found in the original code that the path of that file was incorrect. It needed to add the ../ before, because it was calling to a file in another folder, not from the master, but from one of the subfolders.
Thanks, guys!

How can i solve an issue in writing data in specific file in my clr project?

I am trying to add some data to a specific file in my project. I am doing that in the function below.
void Files::write_employee(employee employeeObject)
{
fstream infile;
infile.open("employeeFile.txt",ios::in|ios::out|ios::app);
string record;
char delimiter='#';
record=employeeObject.get_id()+delimiter;
record+=employeeObject.get_name()+delimiter;
record+=employeeObject.get_password()+delimiter;
record+=employeeObject.get_age()+delimiter;
record+=employeeObject.get_gender()+delimiter;
record+=employeeObject.get_MaritalStatus()+delimiter;
record+=employeeObject.get_ministryName()+delimiter;
record+=employeeObject.get_departmentName()+delimiter;
record+=employeeObject.get_salary()+delimiter;
record+=employeeObject.get_photoPath()+delimiter;
record+=employeeObject.get_photoFileName()+delimiter;
if (infile.fail())exit(1);
else {infile<<record;
infile.close();}
}
This function explains how to add data to my file through save the entered data
in an object and save this values in string record and push it to the file.
The big problem is my file which I am trying to add data in, not created yet.
and I don't know why.
thanks in advance.
You use infile whereas you are outputting to file. While this does not affect the program code, it makes no sense and break your program readability. Use outfile instead.
Remember that it is just like cout << and cin >> for the standard I/O.
Also, try not to use ios::in when your purpose is only to output to the file and vise versa.
According to std::fstream::open example at cplusplus.com, your code is correct and the file must be created. First try to specify an absolute file path to a location that you have write access. If it does not work, print the error message using the following line of code:
cerr << "Error: " << strerror(errno);

Including data file into C++ project

I have a data file data.txt which includes character and numeric data.
Usually I read the data.txt in my program by using file streams like
ifstream infile("C:\\data.txt",ios::in); then use infile.getline to read the values.
Is it anyway possible to have the data.txt file included to the project and compile
it with the project such that when I read the file I do not have to worry about the path
of the file ( I mean I just use something like ifstream infile("data.txt",ios::in) ).
Moreover if I can compile the file with my project I will not have to worry about
providing a separate data.txt file with my release build to anyone else who wants to use
my program.
I do not want to change the data.txt file to some kind of header file. I want to keep the
.txt file as is and somehow package it within my executable that I am building. I still
want to keep using ifstream infile("data.txt",ios::in) and read the lines from the file
but want data.txt file to be with the project just like anyother .h or .cpp files.
I am using C++ visual studio 2010.
It would be kind of someone to provide some insight into the above thing I am trying to
do.
Update
I managed to use the code below to read in the data file as resource
HRSRC hRes = FindResource(GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_TEXT1), _T("TEXT"));
DWORD dwSize = SizeofResource(GetModuleHandle(NULL), hRes); HGLOBAL hGlob = LoadResource(GetModuleHandle(NULL), hRes);
const BYTE* pData = reinterpret_cast<const BYTE*>(::LockResource(hGlob));
but how do I read the separate lines ? Somehow I am unable to read the separate lines. I can't seem to differentiate one line from another.
I can just give you a workaround, if you don't want to worry about the path of the file, you can just:
- add you file to your project
- add a post building event to copy your data.txt file in your build folder.
There was a similar question, that also required inclusion of external file into C++ code. Please check my answer here.
Another way is to include a custom resource in your project, and then use FindResource, LoadResource, LockResource to access it.
You can put the contents of the file in std::string variable:
std::string data_txt = "";
Then use sscanf or stringstream from STL to parse the contents.
One more thing - you will need to handle special characters like '"' by using \ character before each one.
For any kind of file, base on RBerteig anwser you could do something simple as this with python:
This program will generate a text.txt.c file that can be compiled and linked to your code, to embed any text or binary file directly to your exe and read it directly from a variable:
import struct; # Needed to convert string to byte
f = open("text.txt","rb") # Open the file in read binary mode
s = "unsigned char text_txt_data[] = {"
b = f.read(1) # Read one byte from the stream
db = struct.unpack("b",b)[0] # Transform it to byte
h = hex(db) # Generate hexadecimal string
s = s + h; # Add it to the final code
b = f.read(1) # Read one byte from the stream
while b != "":
s = s + "," # Add a coma to separate the array
db = struct.unpack("b",b)[0] # Transform it to byte
h = hex(db) # Generate hexadecimal string
s = s + h; # Add it to the final code
b = f.read(1) # Read one byte from the stream
s = s + "};" # Close the bracktes
f.close() # Close the file
# Write the resultan code to a file that can be compiled
fw = open("text.txt.c","w");
fw.write(s);
fw.close();
Will generate something like
unsigned char text_txt_data[] = {0x52,0x61,0x6e,0x64,0x6f,0x6d,0x20,0x6e,0x75...
You can latter use your data in another c file using the variable with a code like this:
extern unsigned char text_txt_data[];
Right now I cant think of two ways to converting it to readable text. Using memory streams or converting it to a c-string.