#include <assert.h>
#include <errno.h>
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
constexpr int EOK = 0; // not defined by errno.h ??
using namespace std;
char const* m_path = "file.txt";
const int dcmd = 0x1234;
struct FileData
{
int magic;
};
int my_save(struct FileData const & payload)
{
int const fd = open (m_path, O_WRONLY | O_TRUNC | O_CREAT);
if (fd < 0)
{
int const retval = errno;
cerr << "my_save: open '" << m_path << "': " << strerror(retval) << endl;
assert (retval != EOK);
return retval; // Could not open -- retval is non zero!!
}
// Following call reads data and populates the payload
ssize_t n = write(fd, &payload, sizeof (payload));
close (fd);
if (n == -1)
{
int const retval = errno;
cerr << "write '" << m_path << "': " << strerror(retval) << endl;
return retval;
}
else if(n == sizeof (payload))
{
return EOK;
}
else
{
cerr << "write '" << m_path << "': file truncated" << endl;
return EIO;
}
}
int my_load(struct FileData & payload)
{
int const fd = open (m_path, O_RDONLY);
if (fd < 0)
{
int const retval = errno;
cerr << "my_load: open '" << m_path << "': " << strerror(retval) << endl;
assert (retval != EOK);
return retval; // Could not open -- retval is non zero!!
}
// Following call reads data and populates the payload
ssize_t n = read(fd, &payload, sizeof (payload));
close (fd);
if (n == -1)
{
int const retval = errno;
cerr << "read '" << m_path << "': " << strerror(retval) << endl;
return retval;
}
else if(n == sizeof (payload))
{
return EOK;
}
else
{
cerr << "read '" << m_path << "': file truncated" << endl;
return EIO;
}
}
int main()
{
{
struct FileData fileData; // uninitialized
fileData.magic = 0x1234;
const int rc = my_save(fileData);
if (rc != EOK)
return rc;
cout << "Saved " << std::hex << fileData.magic << endl;
}
struct FileData fileData; // uninitialized
const int rc = my_load(fileData);
if (EOK == rc)
{
// SQ why u no let me access data
// fileData will be initialized if we get here
fileData.magic >>= 4;
cout << "Loaded " << std::hex << fileData.magic << endl;
}
return rc;
}
4