-4

Can any one tell me that, how do we read a specific portion of file using c.

I have a file of 1000 Characters and I want to read it in parts eg: First 0 to 100 Characters and then 101 to 200 and so on. I have tried fread() and fseek() but couldn't do it.

I want something like a pointer starts from the beginning of file and reads 100 chars and then moves to 101 position and then again reads 100 chars and so on.

Casper
  • 77
  • 4
  • 5
    Show your code. – axiac Feb 06 '18 at 07:45
  • 4
    When you use `fread` to read the first 100 bytes, then the file pointer will be placed on byte 101, so the next call to `fread` will read from that position onward. It happens automatically exactly what you seem to want. If you create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us, we will be able to help you better. Also please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). – Some programmer dude Feb 06 '18 at 07:46
  • 1
    http://idownvotedbecau.se/beingunresponsive and http://idownvotedbecau.se/nocode/ and (basically) http://idownvotedbecau.se/itsnotworking/ – Some programmer dude Feb 06 '18 at 08:51

1 Answers1

-1

Hope this helps...

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(void)
{
    int fd;
    char line[101] = {0};
    ssize_t readVal;
    int ret;

    /* open the file in question */
    fd = open("tmpp", O_RDONLY);
    if ( fd < 0 )
        exit(EXIT_FAILURE);

    /* read the first 100bytes (0-99)*/
    readVal = read(fd, line, 100); 
    printf("Retrieved first %zu bytes:\n %s\n\n", readVal, line);

    /* read the next 100bytes (100-199)*/
    readVal = read(fd, line, 100); 
    printf("Retrieved second %zu bytes:\n %s\n\n", readVal, line);

    /* jump to location 300, i.e. skip over 100 bytes */
    ret = lseek(fd, 300, SEEK_SET);
    if ( ret < 0 ) {
        close( fd );
        return -1;
    }

    /* read next 100bytes (300-399) */
    readVal = read(fd, line, 100); 
    printf("Retrieved third %zu bytes - at location 300:\n %s\n\n", readVal, line);

    /* close the file descriptor */
    close(fd);
    exit(EXIT_SUCCESS);
}

obviously, the input can be read not as strings...

Omer Dagan
  • 662
  • 5
  • 14