0

ファイルを読み込もうとしています。文字列「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);
}    
4

1 に答える 1

1

You can add sscanf in the moment when you find the mypop string in the file. Add the following line in your while loop:

sscanf(buf,"%*[^=]= %[^\n]",value);

"%*[^=]": This means that scanf capte all characters befor the = and ignore it

" %[^\n]": This means that you are capting all characters after the = till the end of your buffer string (even the space characters). only the space characters in the beggining of the value string will not capted

add it in this way

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++;
 }
于 2013-01-16T16:25:00.340 に答える