I'm writing to the /dev interface of a hardware device on linux. The /dev interface is presented as a linux file, to talk to the device you simply read and write the file. I am using std c++ file wrappers std::fwrite and std::fread because i need access to the file underlying file descriptor for ioctl calls, which is not exposed with the prefered std::ofstream but i digress.
The issue is simple, a write followed by a read fails when using the std:: * calls. It appears to be an issue with fseek but I am unsure. With the fseek code as shown below, successive writes return as if they are a success but no data is written, without fseek code the std::fread call returns an error value. Curiously the linux file functions (write and read) work perfectly, without any fseek mess or anything at all. My question is WHY!?
Linux function version (works perfectly):
bool Write(const std::vector<T> &data)
{
if(write(GetFileDescriptor(),&data[0],sizeof(T) * data.size()) ==
sizeof(T) * data.size())
return true;
return false;
}
std::vector<T> Read(int CountOfT)
{
std::vector<T> buf(CountOfT);
if(read(GetFileDescriptor(), &buf[0], sizeof(T) * CountOfT) !=
sizeof(T) * CountOfT)
throw "stuff"; //i actually use std::optional
return buf;
}
STD Version (fails)
bool Write(const std::vector<T> &data)
{
if(std::fwrite(data.data(), sizeof(T), data.size(), m_fd.get()) <
data.size())
return false;
return true;
}
std::vector<T> Read(int CountOfT)
{
long fileoffset = std::ftell(m_fd.get()); //get current offset
std::fseek(m_fd.get(),0,SEEK_SET); //place offset at file start
std::vector<T> buf(CountOfT);
if(std::fread(&buf[0],sizeof(T),buf.size(),m_fd.get()) < CountOfT)
throw "stuff";
std::fseek(m_fd.get(),fileoffset,SEEK_SET); //reset to where it was
return buf;
}
Aucun commentaire:
Enregistrer un commentaire