我正在尝试从以逗号分隔的文件中读取字符串,并希望在输出期间显示结果并将结果保存为特定格式(看起来像 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 */
}
注意fscanf
中格式前的额外空格
读取的算法是:
while( is reading [a] succesful )
{
ignore comma
read [b]
ignore comma
print {"a": "b"}
}
关于c - 从文件读取数据后动态存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28191376/