In the following programs, there is my structure as
struct binary
{
char *time_str;
uint16_t id;
uint8_t data[8];
};
long usec()
{
struct timeval start;
long mtime;
gettimeofday(&start,NULL);
mtime = start.tv_sec + start.tv_usec;
return mtime;
}
void data_log(struct can_frame *frame_rd)
{
int i;
time_t t = time(NULL);
struct tm *tm = localtime(&t);
struct binary bin;
sprintf(bin.time_str,"%#X.%#X.%#X %#X:%#X:%#X:%#lX",tm->tm_mday,tm-
>tm_mon+1,((tm->tm_year)%100),tm->tm_hour,tm->tm_min,tm->tm_sec,usec());
puts(bin.time_str);
bin.id = frame_rd->can_id;
for(i=0;i<8;i++)
{
bin.data[i] = frame_rd->data[i];
}
fwrite(&bin,sizeof(bin),1,fPtr);
}
int main()
{
struct can_frame frame_rd;
while(1)
{
open_file();
data_log(&frame_rd);
close_file();
}
return 0;
}
Everything works fine if structure in fwrite
function is replaced by other data but for the above structure with time_str (in hex format) while writing into a file in wb
mode, the program crashes. I am sure the problem is near time_stri and fwrite
. Because I tried with other ways and this program works correctly if the program is as follows:
struct binary
{
uint8_t time_yr;
uint8_t time_mon;
uint8_t time_day;
uint8_t time_hr;
uint8_t time_min;
uint8_t time_sec;
uint32_t time_usec;
uint16_t id;
uint8_t data[8];
};
long usec()
{
struct timeval start;
long mtime;
gettimeofday(&start,NULL);
mtime = start.tv_sec + start.tv_usec;
return mtime;
}
void data_log(struct can_frame *frame_rd)
{
int i;
time_t t = time(NULL);
struct tm *tm = localtime(&t);
struct binary bin;
bin.time_day = tm->tm_mday;
bin.time_mon = tm->tm_mon+1;
bin.time_yr = ((tm->tm_year)%100);
bin.time_hr = tm->tm_hour;
bin.time_min = tm->tm_min;
bin.time_sec = tm->tm_sec;
bin.time_usec= usec();
bin.id = frame_rd->can_id;
for(i=0;i<8;i++)
{
bin.data[i] = frame_rd->data[i];
}
fwrite(&bin,sizeof(bin),1,fPtr);
}
int main()
{
struct can_frame frame_rd;
while(1)
{
open_file();
data_log(&frame_rd);
close_file();
}
return 0;
}
The second program works well, with out any crash and writes the data into a file in hex format. But in the second program the times are not written in hex format and to write times in the hex format, the first program is correct and when I use puts
to see the hex values of the time, it shows time in hex format but the program crashes when it executes while writing data into file.
How can I solve this, how can I write times in hex format to the binary file using the structure bin.
In both programs, open_file() and close_file() are two functions to open file in binary mode and to close the file and these are not included inside the programs under this post as most of us know to open a file and close file. It would be great if someone helps in this. Thanks in advance.