-3
"text.txt"라는 파일에서 데이터를 읽고 JSON을 통해 구문 분석하는 프로그램을 만들었습니다. 문자 읽기 방식의 파일 크기를 알고 있습니다. 그래서 for 루프에서 for 루프의 값을 647로 정의하고, 값이 증가하거나 감소하면 어떻게 관리 할 것인가에 대한 도움을 청합니다.c 프로그램에서 파일 처리시 eof (f) 처리
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "jsmn.h"
void error(char *msg)
{
perror(msg);
exit(0);
}
static int jsoneq(const char *json, jsmntok_t *tok, const char *s)
{
if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start && strncmp(json + tok->start, s, tok->end - tok->start) == 0)
{
return 0;
}
return -1;
}
int main(int argc, char const *argv[])
{
int i,n,r;
char buf[1024];
char JSON_STRING[5000];
jsmn_parser p;
jsmntok_t t[2048];
char * fname;
FILE *fp=fopen("text.txt","r+");
FILE *ff;
if(fp==NULL)
{
error("file opening error");
}
for(int i=0; i<647;i++) /////////this if the for loop //////////
{
JSON_STRING[i] = getc(fp);
}
jsmn_init(&p);
r = jsmn_parse(&p,JSON_STRING, strlen(JSON_STRING), t, sizeof(t)/sizeof(t[0]));
if (r < 0){
printf("\nFailed to parse JSON: %d\n", r);
return 1;
}
else{
for (i = 1; i < r; i++){
if (jsoneq(JSON_STRING, &t[i], "RID") == 0)
// for extracting the value of Rid from the complete string
{/* We may use strndup() to fetch string value */
//printf("RID: '%.*s'\n",t[i+1].end - t[i+1].start, JSON_STRING+ t[i+1].start);
printf("- RID: %.*s\n", t[i+1].end-t[i+1].start,JSON_STRING + t[i+1].start);
sprintf(fname,"%.*s",t[i+1].end - t[i+1].start, JSON_STRING+ t[i+1].start);
ff=fopen (fname, "w");
fprintf(ff, "RID: '%.*s'\n",t[i+1].end - t[i+1].start, JSON_STRING+ t[i+1].start);
i++;
}
}
else if (jsoneq(JSON_STRING, &t[i], "DID") == 0) //for Extracting the value of DID from te string recived from the client JSON_STrING
{
/* We may additionally check if the value is either "true" or "false"*/
printf("- DID: %.*s\n", t[i+1].end-t[i+1].start,JSON_STRING + t[i+1].start);
fprintf(ff, "DID: '%.*s'\n",t[i+1].end - t[i+1].start, JSON_STRING+ t[i+1].start);
i++;
//sprintf(fname,"%s_%.*s",fname,t[i+1].end - t[i+1].start, JSON_STRING+ t[i+1].start);
}
else if (jsoneq(JSON_STRING, &t[i],"TS") == 0)
{
/* We may want to do strtol() here to get numeric value */
printf("- TS: %.*s\n", t[i+1].end-t[i+1].start,JSON_STRING + t[i+1].start);
fprintf(ff, "TS: '%.*s'\n",t[i+1].end - t[i+1].start, JSON_STRING+ t[i+1].start);
// sprintf(fname,"%s_%.*s",fname,t[i+1].end - t[i+1].start, JSON_STRING+ t[i+1].start);
}
/* else
{
printf("Unexpected key: %.*s\n", t[i].end-t[i].start,JSON_STRING + t[i].start);}*/
}
printf("JSON parsed : %d\n", r);
printf("output have been generated to the file");
fprintf(ff, "%s\n",JSON_STRING);
fclose(ff);
}
return EXIT_SUCCESS;
fclose(fp);
return 0;
}
코드를 들여 쓰기하십시오. 또한 http://stackoverflow.com/a/26557243/669576을 참조하십시오. 거기에 몇 가지 예가 있습니다. –
@numer 귀하의 게시물을 읽기가 어렵게 만들었 기 때문에 관련없는 코드와 의견을 남겨 두십시오. – UmNyobe