Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unread a file in C++

Tags:

c++

c

io

libc

fstream

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.

like image 762
SMir Avatar asked Oct 22 '22 12:10

SMir


1 Answers

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.

like image 65
Roman Nikitchenko Avatar answered Oct 24 '22 10:10

Roman Nikitchenko