Search code examples
c++fstream

Can I read and write to the same file in Android, using mutexes, without having undefined behaviour?


I'm designing a musical Looper, which is something that, once a first recording is made with x seconds, repeats playing these x seconds and on each iteration, adds new content to the loop.

Since the size of the first recording can vary, I cannot do this with RAM allocated memory, I must place it to disk.

Long story short, I cannot spend the time to close the file and open again on every loop iteration, so I need to write and read from the same file.

If I protect this file by a mutex, can I do that without having undefined behaviour?


Solution

  • Since the size of the first recording can vary, I cannot do this with RAM allocated memory, I must place it to disk.

    Your assumption is simply wrong. Just because size of the recording can vary does not mean you have to put it on disk. For example you could store your recording in a std::vector<unsigned char>. This is a vector holding bytes. You can add or remove any number of bytes you want. Even this is too low level. You better define your own application specific data structure to be able to fluently modify your recording without concerning about files, bytes and the memory.

    If you share a few pieces of your code, people can suggest on that.