从文件读取后动态存储数据

Store data dynamically after reading from a file

我正在尝试从以逗号分隔的文件中读取字符串,并希望在输出期间将结果显示并保存为特定格式(看起来像 JSON 格式)。

我设法从文件中读取和显示数据,但未能以如下例所示的格式动态显示它。相反,它只是在结束前在一行中显示整个字符串。

例如

文件内容:
距离,50 公里,时间,2 小时,日期,2015 年 1 月 1 日等

想要的输出结果:

{"Distance":"50km"}
{"Time":"2hrs"}  
{"Date":"1 Jan 2015"}

实际输出
{“文件的全部内容”:“此处未显示任何内容”}

我已经注释掉了处理读取文件内容直到找到逗号的行,以及以所需格式打印结果的行,因为这些行无法正常工作。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ( int argc, char *argv[] )
{     
  if ( argc != 2 )
  {    printf( "Insert filename you wish to open\n Eg: %s filename\n\n", argv[0] );
  }
 else
   {
    FILE *file = fopen( argv[1], "r" );

    if ( file == 0 )
    {
        printf( "There was an error opening the file\n\n" );
    }
    else
    {
        char a,b;
        while  ( ( a = fgetc( file ) ) != EOF )
        {
            printf( "%c", a,b );
//fscanf(file,"%[^,]",a);/* Read data until a comma is detected,  */
// printf("\nData from file:\n{\"%s\" : \"%s\"}\n\n",a,b); /* Display results into {"A":"B"} format */
        }
        fclose( file );
    }
  }
  return 0;
}

使用此代码:

char a[50], b[50];
while(1 == fscanf(file," %[^,]",a) ) /* Read data until a comma is detected,  */
{
  fgetc( file ); // Ignore , character
  fscanf(file," %[^,]",b); /* Read data until a comma is detected,  */
  fgetc( file ); // Ignore , character
  printf("{\"%s\":\"%s\"}\n",a,b); /* Display results into {"A":"B"} format */
}

Live demo here

注意 fscanf

格式前的额外 space

要读取的算法是:

while( is reading [a] succesful )
{
  ignore comma
  read [b]
  ignore comma
  print {"a": "b"}
}