Robert Whitmer Robert Whitmer - 1 year ago 61
C Question

When read in from a named pipe, do char arrays automatically get a null terminator appended?

I have created a struct which contains the following character arrays.

typedef struct {
char id_size;
char event_size;
char userid[10];
char date[6];
char start_time[4];
char end_time[4];
char event[20];
} CalendarEvent;

I am trying to output these values to the screen after reading from a named pipe into a structue.


fd = open(myfifo, O_RDONLY);
CalendarEvent ev;
ev = reset;
if(read(fd, &ev.id_size, 1) > 0){
printf("%c\n", ev.id_size);
if(read(fd, &ev.event_size, 1) > 0){
printf("%c\n", ev.event_size);
if(read(fd, &ev.userid, 10) > 0){
printf("%s\n", ev.userid);
if(read(fd, &, 6) > 0){
if(read(fd, &ev.start_time, 4) > 0){
printf("%s\n", ev.start_time);
if(read(fd, &ev.end_time, 4) > 0){
printf("%s\n", ev.end_time);
if(read(fd, &ev.event, 20) > 0){
printf("%s\n", ev.event);
//ev.id_size = int(ev.id_size);
//ev.event_size = int(ev.event_size);
ev.userid = ev.userid + '\0';

for(int i=0; i < list.size(); i++){
std::cout<<"\nName: "<<list[i].userid;
std::cout<<"\nDate: "<<list[i].date;
std::cout<<"\nStart time: "<<list[i].start_time;
std::cout<<"\nEnd time: "<<list[i].end_time;
std::cout<<"\nEvent: "<<list[i].event;

However, when I run this program, I receive the following output (for just the cout):

Name: robert123410311608000900meeting
Date: 10311608000900meeting
Start_time: 08000900meeting
End_time: 0900meeting
Event: meeting

Whereas it should be the following:

Name: robert
Date: 103116
Start_time: 0800
End_time: 0900
Event: meeting

I presume this is an issue with the streams reading all the way til it sees a null terminator, but I'm confused why it is not finding one on each element of the struct and only at the end. So I suppose my question is if there is a need for me to manually append on null terminators to these char arrays? If so, would that then affect the length of the char arrays I have made?

Please let me know if there is any other information or context I can give!

Answer Source

When read in from a named pipe, do char arrays automatically get a null terminator appended?

The standard read syscall returns data verbatim.

This is because this call is unaware of destination types: it reads into void*.

You can still print those char arrays without having to append the zero terminator, e.g.:

printf("%.*s\n", static_cast<int>(sizeof ev.end_time), ev.end_time);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download