您好以下代码示例似乎有一些问题,或者它必须对OS内部做一些事情。
#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帮助。
答案 0 :(得分:2)
你应该在列表中加上“\ n”,即
list[len++] = '\n';