Is it possible to store 8 characters (1-byte each) in a variable of type double (8-bytes) in c/c++? -
i migrating legacy fortran77 code c/c++. in fortran77 code, if 8 characters read in file, can stored in variable of type real*8 without problem.
is possible similar thing in c or c++? if so, how it? haven't been able find solutions on internet. need read in 8 characters using c/c++ , store them in variable of type double, passed fortran , corresponds original real*8 variable.
many in advance help.
edit: in response @sixlettervariables, i'll clarify use-case bit more. issue have suggestion know format of each line (i.e. fields strings, numbers) @ runtime, , hence can't know members struct should have statically. fields need occupy contiguous block of memory in order read in.
concretely, in 1 run of program format of each line might be: f1:string, f2:number, f3:number, f4:string, in f1:string, f2:string, f3:string, f4:number, f5:number. first case i'd need:
struct { char[8] f1; double f2; double f3; char[8] f4}
for second i'd need:
struct { char[8] f1; char[8] f2; char[8] f3; double f4; double f5}
perhaps there way templates?
you not need store them in double
because fortran needed that. in fact, absolutely should not in c/c++ code.
simply store character data in character array.
if you're mixing fortran , c/c++, 2 have no idea 1 outside of abi. c side can claim fortran interface takes character array, when in fact expecting array of doubles. , same true fortran side.
from c side:
extern void fchars(char* str, int length); /* ... */ int flength = 0; /* optional: length of string in fortran terms */ char str[9]; /* in c/c++ add 1 \0 @ end */ /* read in block of 8 */ fgets(str, sizeof(str), fp); /* @ point if know 8 characters space padded end * have no more work do, otherwise may need fill right * spaces. */ { size_t ii = sizeof(str) - 1; while (ii > 0 && str[ii - 1] == '\0') { str[ii - 1] = ' '; flength = ii--; /* optional: keep track of our unpadded length */ } } /* once you've space padded string can call fortran method. * if fortran method accepts string of unknown length, supply * `flength`. if fortran method expects string of fixed length, pass * size of `str` (excluding '\0') instead. */ fchars(str, flength);
as long follow abi requirements of fortran compiler (e.g. cdecl, hidden string lengths passed interleaved) c/c++ code, you'll fine.
Comments
Post a Comment