Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm trying to learn C++ and I would interested in how I could write better code. The code should be independent of the architecture it is running on. What I want to do is writing some binary data to /dev/rfkill so that I can change some settings. The target is an embedded system so the program does run with root privileges and the program is using the Qt framework.

This is the code I currently have and which does what I want:

    rfkill_event event;
    event.type = RFKILL_TYPE_ALL;
    event.op = RFKILL_OP_CHANGE_ALL;
    event.soft = RFKILL_ACTION_UNBLOCK;

    QFile file("/dev/rfkill");
    if (!file.open(QIODevice::WriteOnly))
        quit();

    QDataStream out(&file);
    if (-1 == out.writeRawData((char*)(&(event.idx)), sizeof(event.idx))) {
        file.close();
        quit();
    }
    if (-1 == out.writeRawData((char*)(&(event.type)), sizeof(event.type))) {
        file.close();
        quit();
    }
    if (-1 == out.writeRawData((char*)(&(event.op)), sizeof(event.op))) {
        file.close();
        quit();
    }
    if (-1 == out.writeRawData((char*)(&(event.soft)), sizeof(event.soft))) {
        file.close();
        quit();
    }
    if (-1 == out.writeRawData((char*)(&(event.hard)), sizeof(event.hard))) {
        file.close();
        quit();
    }
    file.close();
    quit();

and the struct looks like this:

struct rfkill_event {
    __u32 idx;
    __u8  type;
    __u8  op;
    __u8  soft, hard;
};

The code is taken and adapted from the rfkill program.

I've removed __attribute__((packed)) from the struct because of the pitfalls mentioned here.

I'm using the writeRawData function instead of the << operator to write the data. The reason for this is that this code should work on big and little endian machines.

Are my assumptions correct and do you have any suggestions on how I could improve this code (besides not having any error handling)?

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.