fgets 不会自动丢弃换行符‘\n’ 被这个函数坑了下

原函数:
char *Is_ip6Get(char *is_ip6, char *hostname){
FILE *fp = NULL;
char temp[512];
char path[1024];
sprintf(path, "%s%s", IS_IP6, hostname);

if (access(path, F_OK)) return NULL;

if (NULL == (fp = fopen(path, "r"))) return NULL;

if (fp){
fgets(temp, 1024, fp);
is_ip6 = temp;
}
return is_ip6;
}
一下代码是输出到页面js的:
if(IPv6)
printf("var IPv6=\"%s\";\n", IPv6);
else
printf("var IPv6=\"\";\n");

会出现以下问题:
var IPv6=“1314
”;
页面就会报错


原因:
fgets函数不会自动丢弃换行符\n

改进函数:

char *Is_ip6Get(char *is_ip6, char *hostname){
FILE *fp = NULL;
char temp[512];
char path[1024];
int len = 0;
sprintf(path, "%s%s", IS_IP6, hostname);

if (access(path, F_OK)) return NULL;

if (NULL == (fp = fopen(path, "r"))) return NULL;

if (fp){
fgets(temp, 1024, fp);
if(!(strncmp(temp, "(null)", 6)))
return NULL;
len = strlen(temp);
temp[len - 1] = '\0';
is_ip6 = temp;
}
return is_ip6;
}

你可能感兴趣的:(C语言)