I am currently doing a research project on VANETs (vehicular Ad hoc networks). I am using 4 laptops installed with ubuntu 12. and above. So, my GPS displays the time stamp in the format (hh:mm:ss.xxx) where xxx is the millisecond. I have tried using gettimeofday() and other date and time functions, but none seems to give me the same required time format output. nevertheless the command on the terminal ( date +"%T.%3N") gives me the exact format as mentioned above. Since, I need this output to be saved in an external file. I have tried using a bash script inside my c program. But I am unable to print a new line in the file from the main using file handling fopen() to insert a new line in the file.
Using this code. I was able to print the time in required format in the file(datebash.csv) , but the problem is that I need to add new line to the same file from the main() using file pointer. But the new line is not getting added to the file and the time is being printed in the same line of the datebash.csv file.
My C program is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <sys/timeb.h>
#define SHELLSCRIPT "\
#/bin/bash \n\
now=$(date +'%T.%3N') \n\
printf \"$now \" >> datebash.csv \n\
printf \" \" >> datebash.csv \n\
"
int main()
{
int i,a=3,b=3,j;
FILE *fp;
puts("Will execute sh with the following script :");
puts(SHELLSCRIPT);
puts("Starting now:");
system(SHELLSCRIPT); // calls the bash script above and runs(SHELLSCRIPT)
for(i=0;i<300;i++) // just to have a few milliseconds to lapse doing this loop
{ a+b*100;}
system(SHELLSCRIPT); // calls the bash script again and prints the result in the same file(datebash.csv)
fp = fopen ("datebash.csv", "a+ "); // I am opening from here the same file datebash.csv so That I can print a new line to it.
if(fp==NULL)
{
printf("Error!");
exit(1);
}
fseek(fp,0,SEEK_END); // placing cursor at end of file to insert new line here
fprintf(fp ,"\n"); //printing new line
system(SHELLSCRIPT);***//the problem is here.. the new line is not getting printed in the datebash.csv when the function is called from here. the time is getting printed in the first line itself.***
return 0;
}
Thanks