我正在尝试读入一个文件,找到字符串“myprop”,“myprop”后面将是一个“=”符号,然后是一个数字。我需要将该数字作为字符串打印出来,去掉空格和注释。我能够找到“myprop”字符串,然后我相信我应该使用 fscanf 但我遇到了麻烦。
const char *get_filename_property()
{
const char *filename = "myfile.properties";
const char *propkey = "myprop";
char buffer[100], *buffPtr, lastChar, value[50];
int line_num=1, i=0;
FILE *fp;
fp=fopen("myfile.properties", "r");
if (fp == NULL)
perror("Error opening file\n\n");
while(fgets(buffer, 100, fp) != NULL)
{
if((strstr(buffer, propkey)) != NULL)
{
printf("Myprop found on line: %d\n", line_num);
printf("\n%s\n", buffer);
}
line_num++;
}
if (fp)
fclose(fp);
}
int main(int argc, char *argv[])
{
get_filename_property();
system("pause");
return(0);
}
最佳答案
当您在文件中找到mypop
字符串时,您可以添加sscanf
。在 while 循环中添加以下行:
sscanf(buf,"%*[^=]= %[^\n]",value);
"%*[^=]"
:这意味着 scanf 捕获 =
之前的所有字符并忽略它
"%[^\n]"
:这意味着您要对 =
之后的所有字符进行大写,直到缓冲区字符串末尾(甚至是空格字符) 。只有值字符串开头的空格字符不会被大写
按照这样的方式添加
while(fgets(buffer, 100, fp) != NULL)
{
if((strstr(buffer, propkey)) != NULL)
{
printf("Myprop found on line: %d\n", line_num);
printf("\n%s\n", buffer);
sscanf(buf,"%*[^=]= %[^\n]",value);
printf("\nvalue is %s\n", value);
break;
}
line_num++;
}
关于c - 如何在特定字符串后打印值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14362869/