Unread file in C ++

I am trying to read files that are simultaneously being written to disk. I need to read pieces of a certain size. If the read size is less than a certain size, I would like it to not read the file (something like what ungetc does, instead for char []) and try again. Adding to bytes already read is not an option for me.

How is this possible?

I tried to save the current position with:

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

and then reading the file and returning the pointer to its randomized position.

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

But it does not seem to work.

+5
source share
2 answers

Replacing my previous sentences with the code I just checked (Ubuntu 12.04 LTS, 32 bit). GCC is 4.7, but I'm sure this is a 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;
}

, , 5 , .

+3

fseek :

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

, - , open, fopen.

0

All Articles