2014-11-06 37 views
-1

我目前正在做一个关于VANETs(车载Ad hoc网络)的研究项目。我正在使用安装了Ubuntu 12及更高版本的4台笔记本电脑。所以,我的GPS以格式(hh:mm:ss.xxx)显示时间戳,其中xxx是毫秒。我曾尝试使用gettimeofday()和其他日期和时间函数,但似乎没有给我所需的相同时间格式输出。不过终端上的命令(日期+“%T.%3N”)给了我上面提到的确切格式。因为,我需要将此输出保存在外部文件中。我曾尝试在我的c程序中使用bash脚本。但我无法在主文件中使用处理fopen()在文件中打印新行以在文件中插入新行。C程序的时间戳在hh:mm:ss.xxx毫秒和文件处理问题

使用此代码。我可以在文件(datebash.csv)中以所需格式打印时间,但问题是我需要使用文件指针从main()向同一文件添加新行。但新行没有被添加到文件中,并且时间正在打印在datebash.csv文件的同一行中。

我的C程序如下:

#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; 
    } 

感谢

+0

你能告诉我们你当前的进度吗? – 2014-11-06 05:49:16

+0

以上是我的简单代码@Sourav Ghosh – Shezwan91 2014-11-06 07:44:02

回答

0

如果我明白了,你想要写一个文件,带有时间戳,随后, 接着另一个时间 邮票。 ,并且您想通过终端上的date+"%T.%3N生成时间戳。

终端:::上

(date +"%T.%3N") >> file.csv 

但是,如果你想编写一个程序来做到这一点(伪代码)

fn = open("file.csv", O_append, S_iwrite); 
check that open was successful, I.E. fn >= 0 
if (0 <= fn) // actually, expect fn to be greater than 2 
{ 
    char buffer[30] = {0}; 

    while(1) 
    { 
     read GPS value into buffer 
     write (fn, buffer, strlen(buffer) ); 
     fflush(fn); 
     memset(buffer, 0x00, sizeof buffer); 
     strcat(buffer, " ,"); 
     // if the reading of the GPS value is not self pacing, then 
     // use sleep(5); or something similar here 
    } 
} 

你可能想添加一些办法关闭档案退出

+0

谢谢..但我可以通过我的新代码获得gps时间和系统。现在的问题是试图在main()文件中插入新的行或空间(datebash.csv) – Shezwan91 2014-11-06 07:20:13