Search code examples
cfileposix

File created with fmemopen has no contents after writing


I have some files on disk that I want to read in and concatenate. I don't want to create a new temporary file on disk. So I decided to use fmemopen to read/write to memory and access it using FILE APIs (I had already written other code that just dealt with a single file).

Excluding error checking, I have essentially:

#define MODE_APPEND "a"

int main(int argc, char *argv[]) {    
  off_t concatenated_file_size = 0;
  for (int i = 1; i < argc; i++) {
    concatenated_file_size += get_file_size(argv[i]);
  }

  char *buf = nullptr;
  FILE *concatenated_file = fmemopen(buf, concatenated_file_size, MODE_APPEND);

  for (int i = 1; i < argc; i++) {
    FILE *file_to_concat = open_file(argv[i]);
    int c;
    while ((c = fgetc(file_to_concat)) != EOF) {
      fputc(c, concatenated_file);
    }
  }
  rewind(concatenated_file);
  int prevchar = fgetc(concatenated_file);
}

get_file_size just uses stat and open_file is just fopen with error checking - both work correctly from my testing.

However, prevchar is always EOF - somehow nothing is being written to the FILE* returned by fmemopen. Is this how this API is supposed to work? Am I doing something incorrectly?


Solution

  • You can't read from a write-only (append) file stream. Using "a" only allows you to append data, not to read from the stream. Use "a+" or "w+" instead — probably "w+".

    If you supplied the buffer (rather than a null pointer), presumably you could access the contents directly by copying from the buffer. You could use that to see whether the buffer contains what you expect. With an automatically allocated buffer (you specify a null pointer to fmemopen()), you don't have that option.