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

标签 c json csv

我正在尝试从以逗号分隔的文件中读取字符串,并希望在输出期间显示结果并将结果保存为特定格式(看起来像 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中格式前的额外空格

读取的算法是:

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

关于c - 从文件读取数据后动态存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28191376/

相关文章:

c++ - 如何在 gdb 中保存设置?

c - 以 '\' 开头并后跟数字(例如 '\234')的字符是什么意思?

javascript - 解析 "... has no method ' 替换时 JSON 错误'"

python - 如何在 Python 中从 CSV 文件中提取 JSON 对象?

mysql - phpmyadmin 插入 csv 文件

c++ - powerpc Maliit 框架交叉编译问题

Python RabbitMQ 连接由子进程继承

javascript - 解析 "Streaming"JSON

java - java 上的 json(包含很少的对象)到 TreeMap

java - 如何使用 BufferedReader 在 java 中复制并写入文本文件