I want to pass a character buffer to a proc entry (say /proc/my_file) from my program. This character buffer contains my structure's elements which is of the form:
struct my_table { char src_ip[4]; char dest_ip[4]; int out_flag; }my_t;
I assign the elements of my_table and copy its contents to an unsigned char buffer as follows:
memcpy(buffer, &my_t, sizeof(struct my_table));
Then I write the buffer's contents into a proc entry created by me (by the name my_file) as:
write(fd, buffer, sizeof(buffer));
where fd is the file descriptor returned by open() after opening the /proc/my_file with O_WRONLY | O_APPEND flags.
What I couldn't understand is that I can only see the first character string i.e my_t.src_ip in this case to be written to /proc/my_file (did a
cat /proc/my_file
to check the content written) and subsequently I observed that the write() operation to /proc/my_file ends as soon as it encounters a null character in the buffer content.
Can I know why does this happen and how to solve this problem of writing a structure's contents into a /proc entry?
Edit: SSCCE for my question: The structure:
struct my_iptable {
char protocol[5]; // to check whether the protocol mentioned is tcp/udp/icmp
char src_ip[16]; // source ip address
char dest_ip[16]; // destination ip address
char src_net_mask[16]; // source net mask
char dest_net_mask[16]; // destination net mask
int src_port; // source port number
int dest_port; // destination port number
char action[8]; // either block or unblock
int delete_rule; // gets the rule number to be deleted
int print_flag; // is set if we are asked to print the rules that have been set
int out_flag; // is set if the packet is outbound, else set to 0;
};
The assignment of my_ipt to null:
struct my_iptable my_ipt; memset(&my_ipt, '\0', sizeof(struct my_iptable));
I have assigned my_ipt's fields properly.
The copying to buffer and writing to proc part:
unsigned char write_buf[sizeof(struct my_iptable)];
memcpy(write_buf, &my_ipt, sizeof(struct my_iptable));
int proc_fp = open("/proc/minifw", O_WRONLY | O_APPEND);
if(proc_fp < 0) {
printf("Couldn't open /proc/minifw for writing\n");
exit(EXIT_FAILURE);}
if(write(proc_fp, write_buf, sizeof(struct my_iptable)) == -1) {
printf("There was an error writing to minifw buffer\n");
exit(EXIT_FAILURE);
}
I hope this gives you appropriate info on what I want to understand.
Thanks!
write(fd, &my_t, sizeof(struct my_table))directly ?.. - xtof pernod