从C中的文件读取名称/值对 [英] Read name value pairs from a file in C
本文介绍了从C中的文件读取名称/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用C打开一个.txt文件,并读取.txt文件中的名称值对以及每个变量中的每个值. txt文件只有3行.
I want to open a .txt file in C and read the name value pairs in the .txt file and each value in a different variable. The txt file has only 3 lines.
Name1 = Value1
Name2 = Value2
Name3 = Value3
我想提取与名称1、2和3对应的值并将它们存储在变量中.我该怎么办?
I want to extract the values corresponding to name 1, 2 and 3 and store them in a variable. How do I go about it?
推荐答案
#include <string.h>
char *token;
char *search = "=";
static const char filename[] = "file.txt";
FILE *file = fopen ( filename, "r" );
if ( file != NULL )
{
char line [ 128 ]; /* or other suitable maximum line size */
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
// Token will point to the part before the =.
token = strtok(line, search);
// Token will point to the part after the =.
token = strtok(NULL, search);
}
fclose ( file );
}
剩下的事我留给你做.
这篇关于从C中的文件读取名称/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文