views:

43

answers:

3

Can you set any index of array as starting index i.e where to read from file? I was afraid if the buffer might get corrupted in the process.

#include <stdio.h>

int main()
{
    FILE *f = fopen("C:\\dummy.txt", "rt");

    char lines[30]; //large enough array depending on file size

    fpos_t index = 0;

    while(fgets(&lines[index], 10, f)) //line limit is 10 characters
    {
        fgetpos (f, &index );
    }

    fclose(f);
}
A: 

lines[index] is the index'th character of the array lines. Its address is not the index'th line.

If you want to skip to a particular line, say 5, then in order to read the 5th line, read 4 lines and do nothing with them, them read the next line and do something with it.

If you need to skip to a particular BYTE within a file, then what you want to use is fseek().

Also: be careful that the number of bytes that you tell fgets to read for you (10) is the same as the size of the array you are putting the line into (30) - so this is not the case right now.

If you need to read a part of a line starting from a certain character within that line, you still need to read the whole line, then just choose to use a chunk of it starting someplace other than the beginning.

Both of these examples are like requesting a part of a document from a website or a library - they're not going to tear out a page for you, you get the whole document, and you have to flip to what you want.

eruciform
A: 

Not like this no. There is a function called fseek that will take you to a different location in the file.

Your code will read the file into a different part of the buffer (rather than reading a different part of the file).

Daniel
+1  A: 

You can, but since your code is trying to read the full contents of the file, you can do that much more directly with fread:

char lines[30];

// Will read as much of the file as can fit into lines:
fread(lines, sizeof(*lines), sizeof(lines) / sizeof(*lines), f);

That said, if you really wanted to read line by line and do it safely, you should change your fgets line to:

// As long as index < sizeof(lines), guaranteed not to overflow buffer
fgets(&lines[index], sizeof(lines) - index, f);
R Samuel Klatchko