所以我的文件有这个内容:
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
感谢任何帮助
答案 0 :(得分:1)
处理此类文件的最佳策略是:
// 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
}