如何读取在文件中间找到的变量

时间:2018-04-03 17:47:48

标签: c file

所以我的文件有这个内容:

Name: Bob Charles
Address: 10 strawberry avenue, port
Age: 19
Tel num: 2383234
Balance: $100.00

我想读取余额并将其存储在浮点变量中。如果我使用fseek它只适用于这个特定的人,因为另一个人可能有不同的地址,平衡等。我试图跟随作为第二个选项:

FILE *fp;
fp = fopen(query, "r");
fscanf(fp, "\n\n\n\n Balance: $%f", &newBal);    
fclose(fp);
printf("bal: %d", newBal);

这会将newBal打印为0

感谢任何帮助

2 个答案:

答案 0 :(得分:1)

处理此类文件的最佳策略是:

  1. 阅读一行文字。
  2. 决定如何解释该行的内容。
  3. 重复直到没有更多行。
  4. // Make it as large as you need
    #define LINE_SIZE 200
    
    char line[LINE_SIZE];
    FILE *fp;
    fp = fopen(query, "r");
    if ( fp == NULL )
    {
       // Deal with error
       exit(1);
    }
    
    while ( fgets(line, LINE_SIZE, fp) != NULL )
    {
        processLine(line);
    }
    
    fclose(fp);
    

    其中processLine可以定义为:

    void processLine(char* line)
    {
        char const* nameToken = "Name:";
        char const* addressToken = "Address:";
        char const* ageToken = "Age:";
        char const* telNumToken = "Tel num:";
        char const* balanceToken = "Balance:";
    
        if ( startsWith(line, nameToken) )
        {
            // Deal with name
        }
    
        else if ( startsWith(line, addressToken) )
        {
            // Deal with address
        }
    
        else if ( startsWith(line, ageToken) )
        {
            // Deal with age
        }
    
        else if ( startsWith(line, telNumToken) )
        {
            // Deal with tel number
        }
    
        else if ( startsWith(line, balanceToken) )
        {
            // Deal with balance
        }
    }
    

    startsWith可以定义为:

    bool startsWith(char* line, char const* token)
    {
       return (strncmp(line, token, strlen(token)) == 0);
    }
    

答案 1 :(得分:-1)

您可以使用fgets逐行读取文件。

ssize_t read = -1;

size_t len = 0;

FILE * file = NULL;

file = fopen("file.txt", "r");

if (file == NULL)
{
    // handle error
}

char line[256];

size_t line_sz = sizeof(line) - 1;

while (fgets(line, line_sz, file) != NULL)
{
    char *key = NULL;

    char *value = NULL;

    sscanf(line, "%s:%s", &key, &value);

    // handle key and value
}