[R] read file with readBin (the file was saved with a C-routine)

Duncan Murdoch murdoch at stats.uwo.ca
Wed Jun 28 18:37:40 CEST 2006


On 6/28/2006 11:48 AM, Jörn Schulz wrote:
> Hello!
> 
> I have problems with using of "readBin" to read files, which was written in C with "fwrite". In the C-File there is the following Code:
> 
> fwrite(MyitINI,sizeof(itINItype),1,outfile);
> 
> where MyitINI is a structure of the following form
> 
> typedef struct{
>  int  KernelFileSave;      /* Determined, if Systemmatrix saved or not.*/
>  char KernelFileName[200]; /* A-Matrix name                            */
>  char StartFileName[200];  /* Startguess (optional)                    */
>  int XSamples;             /* No of samples on 1. axis of recon image  */
>  int YSamples;             /* No of samples on 2. axis of recon image  */
>  float DeltaX;             /* Sampling distance 1. axis of recon image */
>  float DeltaY;             /* Sampling distance 2. axis of recon image */
>  float Xmin;               /* 1. sample position 1.axis of recon image */
>  float Ymin;               /* 1. sample position 2.axis of recon image */
>  }  itINItype;
> 
> I thought the following use of "readBin" sould it do, but it doesn't
> 
> KernelFileSave <- readBin( con, integer(), n=1, size=4 )
> KernelFileName <- readBin( con, character(), n=1 )

You've written out 200 characters, but are only reading up to the first 
null.  I think you want readChar here, or you want to change the way you 
write the struct.

> StartFileName <- readBin( con, character(), n=1 )

Same here.

> XSamples <- readBin( con, integer(), n=1, size=4 )
> YSamples <- readBin( con, integer(), n=1, size=4 )
> DeltaX <- readBin( con, numeric(), n=1, size=4 )
> DeltaY <- readBin( con, numeric(), n=1, size=4 )
> Xmin <- readBin( con, numeric(), n=1, size=4 )
> Ymin <- readBin( con, numeric(), n=1, size=4 )
> 
> I think there is a problem if I read the character. Have you any ideas ???
> 
> Thanks for help.
> Jörn Schulz.

I would also worry about the alignment of the fields within the struct, 
though it is probably okay given that everything is a multiple of 4 
bytes long.

Duncan Murdoch



More information about the R-help mailing list