Skip to content

Instantly share code, notes, and snippets.

@kolyuchiy
Last active December 26, 2015 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kolyuchiy/7152532 to your computer and use it in GitHub Desktop.
Save kolyuchiy/7152532 to your computer and use it in GitHub Desktop.
Read from file ignoring EOF
int myfile_read_buffer(void *opaque, uint8_t *buf, int buf_size)
{
MyFileContext *file = opaque;
FILE *fd = file->file;
void *b = malloc(buf_size);
size_t bytes_left = buf_size;
size_t total_bytes_read = 0;
void *p = b;
while (bytes_left > 0) {
if (fd == NULL) {
free(b);
return total_bytes_read;
}
ssize_t bytes_read = fread(p, 1, bytes_left, fd);
if (bytes_read < 0) {
free(b);
return bytes_read;
}
else if (bytes_read == 0) { // EOF - wait and repeat
if (myfile_get_finished_writing(opaque)) {
total_bytes_read += bytes_read;
goto finish;
}
else {
usleep(1000 * 100); // 100ms
clearerr(fd);
continue;
}
}
total_bytes_read += bytes_read;
p += bytes_read;
bytes_left -= bytes_read;
}
finish:
memcpy(buf, b, total_bytes_read);
free(b);
return total_bytes_read;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment