Reputation: 2593
I am having a weird issue when i do a pwrite a struct to a file. It adds a single byte with next to a char entry in the struct. When i tried to write the char alone to a file it correctly wrote a single byte. Could some one tell me why the single byte got added??
int main(){
typedef struct pcap_hdr_s {
guint32 magic_number; /* magic number */
guint16 version_major; /* major version number */
guint16 version_minor; /* minor version number */
gint32 thiszone; /* GMT to local correction */
guint32 sigfigs; /* accuracy of timestamps */
guint32 snaplen; /* max length of captured packets, in octets */
guint32 network; /* data link type */
guint32 ts_sec; /* timestamp seconds */
guint32 ts_usec; /* timestamp microseconds */
guint32 incl_len; /* number of octets of packet saved in file */
guint32 orig_len; /* actual length of packet */
guint16 fcf;
char seqno;
guint16 dpan;
guint16 daddr;
guint16 saddr;
gint16 payload_data;
} pcaprec_hdr_t;
pcaprec_hdr_t packet_header;
packet_header.magic_number = PCAP_MAGIC;
packet_header.version_major = 2;
packet_header.version_minor = 4;
packet_header.thiszone = 0;
packet_header.sigfigs = 0;
packet_header.snaplen = 65535;
packet_header.network = 195;
struct timeval tv;
gettimeofday(&tv, NULL);
packet_header.ts_sec = tv.tv_sec;
packet_header.ts_usec = tv.tv_usec;
packet_header.incl_len = 11;
packet_header.orig_len = 13;
packet_header.seqno = 255;
packet_header.dpan = 65535;
packet_header.daddr = 65535;
packet_header.saddr = 65535;
packet_header.payload_data = 8;
int fd = open("sample.cap", O_CREAT | O_WRONLY);
printf("Bytes written: %d \n",pwrite(fd, &packet_header, sizeof(packet_header),0));
}
The struct has a char var "seq" and next to the seq no value a single byte of random value gets added in the file.
Upvotes: 0
Views: 600
Reputation: 7946
Your structure contains a char
data member and you probably have word-alignment on. See if you can find a "pack" option in the compiler.
You can probably use a #pragma pack(1)
or similar pragma (pragma's are implementation specific) to change the alignment for a particular set of classes.
Be careful though, the compiler word-aligns for performance reasons. The memory bus typically works on word boundaries, so you could end up requiring two fetchs for each word that straddles the word boundary thereby slowing memory access down a bit.
You might want to stream the structure members out individually if you're concerned about the added bytes in the file.
Upvotes: 6