tags:

views:

247

answers:

4

In C, if I read a line from the file by function fgetc, there might be a stack overflow. Suppose that some has written a program which outputs a a huge line of ASCII data in one line on a particular file. How can I read that data in my C program to screen? I know that I can read only, say 100 character at once but I don't know how can I start reading from a specific position.

A: 

Consult fseek() and ftell().

Amit
+2  A: 

You can use the read() function to read in a set size at a time (say 100 bytes). You just keep doing this is a loop until read() indicates that there's nothing left to read. read() returns the number of bytes read, so when it returns less than the number of bytes you requested you know you're done.

Sean
do you mean fread() ?
Adrien Plisson
Does fread() allow reading from a specific position? No!
Amit
Fread certainly allows reading from a specific position. fread() will always read from the 'current position' of the file (which is specific and can be modified by fseek).
William Pursell
Of course. But, there is no way to specify the current pos in fread.
Amit
A: 

also look at mmap()

mmap the whole file and you can treat the result as as if you read the whole file into an array. With the bonus of not having to allocate any memory.

Whoever downvoted me, I'd really like to see your explanation of why seek&read is better than mmap for this

gnibbler
I didn't down vote you but my objection would be it is that it doesn't solve the general problem class. It will work in this specific case but the exact same problem exists with things like sockets, external devices, etc., where it won't. Given what seems to be the relative inexperience of the OP it is better to teach best practices than suggesting things that will likely just confound him if he isn't prepared.
Duck
A: 

you can dynamically allocate a array of char using malloc(), then read your file character by character using fgetc(). when you reach the end of your buffer, you call realloc() to extend your buffer, then continue reading characters. this way, the only error you can have is an "out of memory" error.

char *buffer = malloc( 200 );
unsigned int buffer_size = 200;
unsigned int current = 0;
char read;

do
{
    read = fgetc( stream );
    if ( current >= buffer_size - 1 )
    {
        buffer_size += 200;
        buffer = realloc( buffer, buffer_size );
    }
    buffer[current++] = read;
}
while ( read != '\n' );
buffer[current++] = '\0';

(missing in the above code: checking the return value of realloc to handle an out of memory condition)

Adrien Plisson