0

I have a binary file Tetris.ch8 which is 494 bytes. I am trying to open that file from my emscripten project. I used --preload-file to load the file. When I am trying to open the file and read the contents, only 21 bytes are present.

void Emulator::LoadROM(char* filename) {
  std::ifstream fs(filename, std::ios::binary);
  std::stringstream buf;
  buf << fs.rdbuf();
  std::cout << buf.str() << buf.str().length() << std::endl;
  return;
}

This is one of the methods I tried. It prints random characters and 21 as length. I also tried std::filesystem::file_size, ftell, etc to try to get the size. All of them are printing 21.

But when I try it separately, without emscripten, with mingw g++, The file size is printed as 494 (expected)

#include <fstream>
#include <iostream>
#include <sstream>
int main() {
  char filename[] = "resources/Tetris.ch8";
  std::ifstream fs(filename, std::ios::binary);
  std::stringstream buf;
  buf << fs.rdbuf();
  std::cout << buf.str() << buf.str().length() << std::endl;
  return 0;
}

This is working correctly.

Why is the same code behaving differently in emscripten?

I tried it with non binary file, I changed the contents of Tetris.ch8 to "Hello". This is working fine in emscripten. Length is 7 and string is read correctly too.

I don't know what I'm missing here.

2
  • Most probably due to non-null termination of the array pointed to by the pointer. Commented Sep 22, 2024 at 9:54
  • Also always provide a minimal reproducible example of the code that is not working instead of the code that is working. Commented Sep 22, 2024 at 9:56

1 Answer 1

0

Ok, It was unrelated to emscripten. I forgot to put COPYONLY in configure_file in CMakeLists.txt.

configure_file(resources/Tetris.ch8 resources/Tetris.ch8)

changed to:

configure_file(resources/Tetris.ch8 resources/Tetris.ch8 COPYONLY)

It's working as expected now.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.