CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 16

Threaded View

  1. #10
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Writing and Reading Binary data in FORTRAN and C++

    Quote Originally Posted by Vectorprg View Post
    Case1: using ReadFile()
    Code:
    #define BUF_SIZE 5000 
    BOOL bSuccess = FALSE;
    char Buf[BUF_SIZE];
    DWORD dwRead;
    for (;;) 
    { 
      bSuccess = ReadFile( V_hChildStd_OUT_Rd, Buf, BUF_SIZE, &dwRead, NULL);
      if( ! bSuccess || dwRead == 0 )   break; 
    }
    
    const int nDoubles = dwRead / sizeof(double);
    
    for (int i=0; i<nDoubles ; ++i)
    {
        double x = *reinterpret_cast<double*>(&chBuf[i*sizeof(double)]);
    }
    Case2: using fopen_s


    Code:
    double x;
    FILE* pFile;
    fopen_s(&pFile, PathName.Left(PathName.ReverseFind('\\')) + "\\Fortran.bin", "rb");
    fread((char*)&x,1,sizeof(double),pFile);
    fclose(pFile);
    First, you do see that your ReadFile does much more than read. You are reading 5,000 bytes of potential data, and afterwords manipulating the returned buffer, all with the hopes that the number is a valid double.

    The fopen_s (which is not ifstream) does things simply. You are reading sizeof(double) bytes, and that's it. So why are you not doing the same thing with ReadFile()? You know you must read sizeof(double) bytes, you know that the buffer is really a pointer to a double, so why are you doing things so radically different with ReadFile() than for fopen_s?

    Third, if you're confident that your ReadFile approach is supposed to work, why are you not debugging it step by step to see where it breaks down?

    Last, the way you would want to write your code to ensure you're at least in sync with your Fortran program is this:

    For runtime check:
    Code:
    #include <assert.h>
    //...
    assert(sizeof(double) == 8);
    Alternate compile time check: (uses "old" C++ syntax)
    Code:
    char x__[sizeof(double) == 8];
    For the first example, a debug version of your program will abort once it is discovered that sizeof(double) is not 8. For the second example, your program will fail to compile if sizeof(double) is not 8. For the second example, you could also use the newer static_assert().

    Otherwise, your program will potentially run assuming that a double in C++ is the same as a double in Fortran (at least in terms of size) when it isn't.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; April 3rd, 2013 at 02:43 PM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured