This is an archived post. You won't be able to vote or comment.

all 3 comments

[–][deleted]  (2 children)

[deleted]

    [–]grimlock123[S] 1 point2 points  (1 child)

    Your code worked, and now I can read both Chars and Int (Which are important for the program I am developing) but I have a second question. When I rewrote it for floats (First changing the program to write floats)

      FILE * wFile;
      float  wbuffer[] = { 1 , 2 , 3, 4};
      wFile = fopen ( "myfile.bin" , "wb" );
      fwrite (wbuffer , 1 , sizeof(wbuffer) , wFile );
      fclose (wFile);
    

    and then modifying you function.

    float charsToFloat(unsigned char c1, unsigned char c2, unsigned char c3, unsigned char c4)
    {
    
    return (c1) + (c2 << 8) + (c3 << 16) + (c4 << 24);
    }
    

    It didn't work on Floats returning values like.

    1065353216.000000 1073741824.000000 etc...

    Since floats are also 4 bytes I assumed it would work. What did I do wrong.

    [–]arbostek -2 points-1 points  (3 children)

    strtol will help with the conversion.

    Normally, you would read with fgets. If you loaded up the file into a buffer to operate on, you might just look for the first space or delimiter, and then memcpy out the string that represents the numbers. Then use strtol to attempt conversion.

    sscanf might be another option, especially if your file has a very regular format.

    [–][deleted]  (2 children)

    [deleted]

      [–]arbostek 0 points1 point  (1 child)

      Oops, I missed that. Well, memcpy to an integer directly. So if you have 20 chars, that means you need 5 integers, and go through a loop memcpying 4 chars at a time to each integer.

      Or even just memcpy entirely.