c - How to read a char array stored in a file, into a char buffer during runtime -


i'm working in c , i'm modifying existing code.

i have char array stored in file follows:

"\x01\x02\x03" "\x04\x05\x06" "\x07\x08\x09" 

in original source code char array included follows:

const static char chs[] = #include "file.h" ; 

i'm modifying code load file char array during runtime (to exact same result above approach) instead of included pre-processor. first approach read file char buffer, follows:

file *fp; const char *filename = "file.h"; fp = fopen (filename, "rb"); assert(fp != null);  fseek(fp, 0l, seek_end); long int size = ftell(fp); rewind(fp);  // read entire file buffer char *buffer = (char*)malloc(sizeof(char) * size); size_t nrofbytesread = fread(buffer, 1, size, fp); 

however i've discovered not correct. file contains exact code representation of char array, cannot read char buffer , same result include approach.

what best way char array stored in file, char array during runtime?

as you've seen, when read file using fread reads byte byte. doesn't of syntactic processing compiler on source files. doesn't know strings live inside of quotes. doesn't map escape sequences \x01 single bytes.

you have several different possibilities fixing this:

  1. teach program how processing reads file. fair amount of work.
  2. put bytes want file.
  3. pick different encoding file.

to little more #2: if don't want change file-reading code, can create (in case) 9-byte file containing 9 bytes want. since 9 bytes not text, it'll end being "binary" file, won't able straightforwardly edit ordinary text editor, etc. (in fact, depending on tools have available you, might challenging create particular 9-byte file.)

so if can't use #1 or #2, might want go #3: pick brand-new way encode data in file, easier parse #1, easier prepare #2. first thought have file hexadecimal. is, file contain

010203040506070809 

or

010203 040506 070809 

your file-reading code, instead of single call fread, read 2 characters @ time , assemble them bytes array. (i'd sketch out you, compilation waiting has finished, , ought job.)


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -