| 1 | // LAF Base Library |
| 2 | // Copyright (c) 2001-2016 David Capello |
| 3 | // |
| 4 | // This file is released under the terms of the MIT license. |
| 5 | // Read LICENSE.txt for more information. |
| 6 | |
| 7 | #ifdef HAVE_CONFIG_H |
| 8 | #include "config.h" |
| 9 | #endif |
| 10 | |
| 11 | #include <cstdio> |
| 12 | |
| 13 | namespace base { |
| 14 | |
| 15 | // Reads a WORD (16 bits) using in little-endian byte ordering. |
| 16 | int fgetw(FILE* file) |
| 17 | { |
| 18 | int b1, b2; |
| 19 | |
| 20 | b1 = fgetc(file); |
| 21 | if (b1 == EOF) |
| 22 | return EOF; |
| 23 | |
| 24 | b2 = fgetc(file); |
| 25 | if (b2 == EOF) |
| 26 | return EOF; |
| 27 | |
| 28 | // Little endian. |
| 29 | return ((b2 << 8) | b1); |
| 30 | } |
| 31 | |
| 32 | // Reads a DWORD (32 bits) using in little-endian byte ordering. |
| 33 | long fgetl(FILE* file) |
| 34 | { |
| 35 | int b1, b2, b3, b4; |
| 36 | |
| 37 | b1 = fgetc(file); |
| 38 | if (b1 == EOF) |
| 39 | return EOF; |
| 40 | |
| 41 | b2 = fgetc(file); |
| 42 | if (b2 == EOF) |
| 43 | return EOF; |
| 44 | |
| 45 | b3 = fgetc(file); |
| 46 | if (b3 == EOF) |
| 47 | return EOF; |
| 48 | |
| 49 | b4 = fgetc(file); |
| 50 | if (b4 == EOF) |
| 51 | return EOF; |
| 52 | |
| 53 | // Little endian. |
| 54 | return ((b4 << 24) | (b3 << 16) | (b2 << 8) | b1); |
| 55 | } |
| 56 | |
| 57 | // Writes a word using in little-endian byte ordering. |
| 58 | // Returns 0 in success or -1 in error |
| 59 | int fputw(int w, FILE* file) |
| 60 | { |
| 61 | int b1, b2; |
| 62 | |
| 63 | // Little endian. |
| 64 | b2 = (w & 0xFF00) >> 8; |
| 65 | b1 = w & 0x00FF; |
| 66 | |
| 67 | if (fputc(b1, file) == b1) |
| 68 | if (fputc(b2, file) == b2) |
| 69 | return 0; |
| 70 | |
| 71 | return -1; |
| 72 | } |
| 73 | |
| 74 | // Writes DWORD a using in little-endian byte ordering. |
| 75 | // Returns 0 in success or -1 in error |
| 76 | int fputl(long l, FILE* file) |
| 77 | { |
| 78 | int b1, b2, b3, b4; |
| 79 | |
| 80 | // Little endian. |
| 81 | b4 = (int)((l & 0xFF000000L) >> 24); |
| 82 | b3 = (int)((l & 0x00FF0000L) >> 16); |
| 83 | b2 = (int)((l & 0x0000FF00L) >> 8); |
| 84 | b1 = (int)l & 0x00FF; |
| 85 | |
| 86 | if (fputc(b1, file) == b1) |
| 87 | if (fputc(b2, file) == b2) |
| 88 | if (fputc(b3, file) == b3) |
| 89 | if (fputc(b4, file) == b4) |
| 90 | return 0; |
| 91 | |
| 92 | return -1; |
| 93 | } |
| 94 | |
| 95 | } // namespace base |
| 96 | |