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.
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.
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
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)