2010-07-31 27 views
1

嗨下面的代码示例似乎有一些问题,或者它必须做一些操作系统的内部。文件操作写入没有发生在新行

#include <stdio.h> 
    #include <stdlib.h> 
    #include <unistd.h> 
    #include <string.h> 
    #include <sys/types.h> 
    #include <sys/stat.h> 
    #include <fcntl.h> 

    static void usage(); 
    #define MONC_AM_CONF "/tmp/monc.conf" 

int main(int argc, char **argv) 
{ 
     int ch; 
     char list[200]; 
     int len; 
     int fd; 

     memset(list,0,200); 
     if (argc < 11) { 
       usage(); 
       exit(1); 
     } 

     while ((ch = getopt(argc, argv, "N:S:P:H:R:")) != -1) { 
       switch (ch) { 
         case 'N': 
           len = strlen(optarg) + 2; 
           sprintf(list,"%s::",optarg); 
           break; 
         case 'S': 
           sprintf(list+len,"%s::",optarg); 
           len = len + strlen(optarg) + 2; 
           break; 
         case 'P': 
           sprintf(list+len,"%s::",optarg); 
           len = len + strlen(optarg) + 2; 
           break; 
         case 'H': 
           sprintf(list+len,"%s::",optarg); 
           len = len + strlen(optarg) + 2; 
           break; 
         case 'R': 
           sprintf(list+len,"%s ",optarg); 
           len = len + strlen(optarg); 
           break; 
         default: 
           printf ("You specified a parameter I don't " 
               "know about.\n"); 
           break; 
       } 
     } 
     argc -= optind; 
     argv += optind; 

     printf("Total length of string is %d\n",len); 
     printf("The string is %s\n",list); 

     fd = open(MONC_AM_CONF, O_WRONLY|O_CREAT|O_APPEND, 0644); 
     lseek(fd, 0,SEEK_END); 
     write(fd,list,len); 
     close(fd); 

     return 0; 
} 

static void usage() 
{ 
printf("Please provide the command in correct format\n"); 
printf("monc_am_config -N <Comp_Name> -S <Start Script Path> -P <Stop Script Path> -H <HealthCheck Script Path> -R <Recovery Policy>\n"); 

return ; 
} 

当我发出命令时,我得到每次不同的输出文件。 我期待这个程序的执行每次都应该在新行中写入信息,但它正在写入文件中的同一行。

Plz help。

回答

2

你应该追加“\ n”来列出,即

list[len++] = '\n'; 
+2

,并希望199个字符是所有将永远需要 – msw 2010-07-31 08:58:01

+0

感谢快速回复!这个对我有用。 – Arpit 2010-07-31 09:05:04