Read and write to binary files in C?

后端 未结 6 1375
梦如初夏
梦如初夏 2020-11-27 13:02

Does anyone have an example of code that can write to a binary file. And also code that can read a binary file and output to screen. Looking at examples I can write to a fi

6条回答
  •  旧巷少年郎
    2020-11-27 13:29

    I really struggled to find a way to read a binary file into a byte array in C++ that would output the same hex values I see in a hex editor. After much trial and error, this seems to be the fastest way to do so without extra casts. By default it loads the entire file into memory, but only prints the first 1000 bytes.

    string Filename = "BinaryFile.bin";
    FILE* pFile;
    pFile = fopen(Filename.c_str(), "rb");
    fseek(pFile, 0L, SEEK_END);
    size_t size = ftell(pFile);
    fseek(pFile, 0L, SEEK_SET);
    uint8_t* ByteArray;
    ByteArray = new uint8_t[size];
    if (pFile != NULL)
    {
        int counter = 0;
        do {
            ByteArray[counter] = fgetc(pFile);
            counter++;
        } while (counter <= size);
        fclose(pFile);
    }
    for (size_t i = 0; i < 800; i++) {
        printf("%02X ", ByteArray[i]);
    }
    

提交回复
热议问题