Question

I am trying to read files that are simultaneously written to disk. I need to read chunks of specific size. If the size read is less than the specific size, I'd like to unread the file (something like what ungetc does, instead for a char[]) and try again. Appending to the bytes read already is not an option for me.

How is this possible?

I tried saving the current position through:

FILE *fd = fopen("test.txt","r+");
fpos_t position;
fgetpos (fd, &position);

and then reading the file and putting the pointer back to its before-fread position.

numberOfBytes = fread(buff, sizeof(unsigned char), desiredSize, fd) 
if (numberByBytes < desiredSize) {
    fsetpos (fd, &position);
}

But it doesn't seem to be working.

Was it helpful?

Solution

Replacing my previous suggestions with code I just checked (Ubuntu 12.04 LTS, 32bit). GCC is 4.7 but I'm pretty sure this is 100% standard solution.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define desiredSize 10
#define desiredLimit 100

int main()
{
    FILE *fd = fopen("test.txt","r+");
    if (fd == NULL)
    {
        perror("open");
        exit(1);
    }

    int total = 0;
    unsigned char buff[desiredSize];

    while (total < desiredLimit)
    {
        fpos_t  position;
        fgetpos (fd, &position);

        int numberOfBytes = fread(buff, sizeof(unsigned char), desiredSize, fd);
        printf("Read try: %d\n", numberOfBytes);
        if (numberOfBytes < desiredSize)
        {
            fsetpos(fd, &position);
            printf("Return\n");
            sleep(10);
            continue;
        }
        total += numberOfBytes;
        printf("Total: %d\n", total);
    }
    return 0;
}

I was adding text to file from another console and yes, read was progressing by 5 chars blocks in accordance to what I was adding.

OTHER TIPS

fseek seems perfect for this:

FILE *fptr = fopen("test.txt","r+");
numberOfBytes = fread(buff, 1, desiredSize, fptr)
if (numberOfBytes < desiredSize) {
    fseek(fptr, -numberOfBytes, SEEK_CUR);
}

Also note that a file descriptor is what open returns, not fopen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top