2010-07-31 26 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