I am investigating different methods of maintaining state between sessions [of my application running].
One [non-portable] method that was suggested to me [from the #ubuntu IRC chat] was to take advantage of man xattr
:
Extended attributes are name:value pairs associated permanently with files and directories, similar to the environment strings associated with a process.
Source Code: https://github.com/torvalds/linux/blob/master/fs/xattr.c
This would be extremely useful to me if I could get it to work. I am not much of a c or kernel developer though, and can not quite parse how I go about mapping key value pairs to a file.
What I have thus far:
#include <QApplication>
#include <QTextStream>
#include <stdio.h>
#include <sys/xattr.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
char key[] = "foo";
char val[] = "bar";
char dir[] = "/home/akiva/foobar.txt";
ssize_t set = setxattr (dir, key, val, strlen(val), 0); // Returns -1[error]
ssize_t get = listxattr(dir, key, strlen(val) ); // Returns 0
QTextStream(stdout) << QString("SetError: %1 \n"
"GetError: %2 \n"
" Key: %3 \n"
" Val: %4 \n").arg(set).arg(get).arg(key).arg(val);
return a.exec();
}
I am not sure why setxattr
is giving me an error, nor what I should expect from listxattr
which seems to be functioning fine.
I'd like to be able to set
or create a key:value
pair for my foobar.txt
file. In this case, "foo":"bar"
. Subsequently, after setting it, I'd like to be able to get the value from the file /home/akiva/foobar.txt
, something along the lines:
FileClass fc("/home/akiva/foobar.txt"); // A class I will make, similar to QMap
{
fc.insert("foo", "bar");
fc.insert("bow", "tie");
}
QString s = fc["foo"]; // s == "bar"
bool hasFoo = fc.contains("foo"); // true
bool hasDoo = fc.contains("doo"); // false
QStringList keys = fc.keys (); // "foo", "bow"
QStringList vals = fc.values(); // "bar", "tie"
Within the class, I would handle all the limitations etc. In any case, I'd like to get a working example of just being able to set and get key value pairs from my files, but I can not find a single example anywhere.
- How can I
set
Key:Value pairs to files usingxattr
? - How can I
get
Key:Value pairs from files usingxattr
? - Do files ordinarily have existing Extended Attributes?