C で .txt ファイルを開き、.txt ファイル内の名前と値のペアと、別の変数内の各値を読み取りたいと考えています。txt ファイルには 3 行しかありません。
Name1 = Value1
Name2 = Value2
Name3 = Value3
名前 1、2、3 に対応する値を抽出し、変数に格納したいと考えています。どうすればいいですか?
最良の方法はこの回答に示されています
#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 );
}
残りはあなたに任せます。
fgets 関数を使用して、ファイルを 1 行ずつ読み取ることができます。文字列のすべての行を返します。次に、strtok 関数を使用して、スペースを区切り文字として使用して文字列をトークンに分割します。したがって、Value1、Value2... が得られます。
ファイルへのポインタを作成します。
FILE *fp;
char line[3];
ファイルを開きます。
fp = fopen(file,"r");
if (fp == NULL){
fprintf(stderr, "Can't open file %s!\n", file);
exit(1);
}
コンテンツを 1 行ずつ読む。
for (count = 0; count < 3; count++){
if (fgets(line,sizeof(line),fp)==NULL)
break;
else {
//do things with line variable
name = strtok(line, '=');
value = strtok(NULL, '=');
}
}
ファイルを閉じることを忘れないでください。
fclose(fp);