Converting a function to read from a string instead of a file in C

I was instructed to update a function that is currently being read in the configuration file from disk and populates the structure:

static int LoadFromFile(FILE *Stream, ConfigStructure *cs)
{
  int tempInt;

   ...

  if ( fscanf( Stream, "Version: %d\n",&tempInt) != 1 )
  {
    printf("Unable to read version number\n");
    return 0;
  }
  cs->Version = tempInt;
   ...

}

which allows us to bypass the configuration entry on disk and instead transfer it directly to memory, roughly equivalent to this:

static int LoadFromString(char *Stream, ConfigStructure *cs)

A few notes:

  • The current LoadFromFile function is incredibly dense and complex, reading dozens of versions of a configuration file with backward compatibility, which makes duplication of common logic a pain.
  • , , , , , . , , , .
  • ( ) fscanf sscanf, (, , ) .
  • C, ++, , .

? FILE *, , ? , .

+3
3

, , POSIX . , mmap(), . IPC, .

POSIX (shm_open() shm_unlink()) FILE * .

#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>

#define MAX_LEN 1024

int main(int argc, char ** argv)
{
    int    fd;
    FILE * fp;
    char * buf[MAX_LEN];

    fd = shm_open("/test", O_CREAT | O_RDWR, 0600);

    ftruncate(fd, MAX_LEN);

    fp = fdopen(fd, "r+");

    fprintf(fp, "Hello_World!\n");

    rewind(fp);

    fscanf(fp, "%s", buf);

    fprintf(stdout, "%s\n", buf);

    fclose(fp);

    shm_unlink("/test");

    return 0;
}

. -lrt gcc Linux.

+2

, , . , , fscanfsscanf, , .

, . ( ) . , , , . malloc , realloc . , , .

, , '\0' . , , ( ).

+3
  • Use mkstemp()to create a temporary file. It takes char *as an argument and uses it as a template for the file name. But it will return a file descriptor.

  • Use tmpfile(). It returns FILE *, but has some security issues , and you must copy the string yourself.

  • Use mmap()( Beej Guide for reference)

+1
source

Source: https://habr.com/ru/post/1737054/


All Articles