简体   繁体   中英

How to programmatically read until a certain character in a file?

My C program writes a .json file. Few of the values in the schema of the .json file is string and has variable length.

I am using jansson library. I will have to read a complete .json object otherwise the library raises an error. So, I cannot read anything less than a complete object or more than the complete object. I am using File I/O in C and reading characters to a char array.

So, if I statically allocate size of the array, but each object varies in number of characters present.

Is there a way to dynamically assign the number of characters to the char array, so that I can read till the end of a particular object?

OR

Is there a way to read in the entire contents of a file without knowing the number of characters in the file?

OR

Should I use a struct to write the .json file? But this will present a problem with braces, commas and colons which will make the struct difficult to maintain.

If you have a file descriptor from which you are reading the json object, you can use getline to dynamically allocate the needed memory for you by setting *lineptr=NULL in your getline call ( see: man getline ). This will read an entire line (up to the newline) of input from your FILE. eg:

char *lineptr = NULL;
size_t n = 0;
ssize_t len = 0;
FILE *jsonfd;

jsonfd = fopen (filename, mode);
if (jsonfd == NULL)
    exit (EXIT_FAILURE);

len = getline (&lineptr, &n, jsonfd);
printf ("read '%zd' characters: %s\n", len, lineptr);

If you have more than 1 line on the input, you can place your getline call in a while loop:

while ((len = getline (&lineptr, &n, jsonfd)) != -1)
{
    process as needed
}

You should be able to parse and write your json string to the file without needing to use a struct to handle the data. Once you have read the information into your character array ( lineptr above) you will have the flexibility to write what you need.

Is there a way to read in the entire contents of a file without knowing the number of characters in the file?

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

long GetFileSize(FILE *fp){
    long fsize = 0;

    fseek(fp,0,SEEK_END);
    fsize = ftell(fp); 
    fseek(fp,0,SEEK_SET);//reset stream position!!

    return fsize;
}

char *ReadToEnd(const char *filepath){
    FILE *fp;
    long fsize;
    char *buff;

    if(NULL==(fp=fopen(filepath, "rb"))){
        perror("file cannot open at ReadToEnd\n");
        return NULL;
    }
    fsize=GetFileSize(fp);
    buff=malloc(fsize+1);
    fread(buff, sizeof(char), fsize, fp);
    fclose(fp);
    buff[fsize]='\0';

    return buff;
}

read an object from a file with jansson :

json_t *obj;
json_error_t error;

obj = json_load_file("data.json", 0, &error);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM