Originally Posted by
movl0x1
But citizen, doesn't that loop assume that I know how many lines
are in the file? What if I'm reading a file and I don't know how
many lines are in it? Wouldn't I read line by line until I come to EOF?
No. Of course, all variables would have to be given proper values, but its no worse than anything else. And if you read EOF, just stop the loop. Here's a more thorough example
Code:
#include <stdio.h>
#include <stdlib.h>
void readlines( FILE *in, FILE *out, unsigned long lines )
{
unsigned long linecount = 0;
int c = 0;
while( (c = fgetc( in )) != EOF && lines > linecount )
{
fputc( c, out );
if( c == '\n' )
linecount++;
}
}
int main( int argc, char **argv )
{
if( argc != 4 )
{
printf( "Read a certain number of lines from a file.\n" );
printf( "Usage: excutable <infile> <outfile> <nlines>\n" );
printf( "\t<infile>\tFile to read lines from.\n" );
printf( "\t<outfile>\tFile to store output in.\n" );
printf( "\t<nlines>\tNumber of lines to read.\n" );
}
else
{
FILE *in, *out;
in = fopen( argv[1], "r" );
if( !in )
{
perror( argv[1] );
return 0;
}
out = fopen( argv[2], "w" );
if( !out )
{
perror( argv[2] );
fclose( in );
return 0;
}
readlines( in, out, strtoul( argv[3], NULL, 10 ) );
fclose( in );
fclose( out );
}
return 0;
}
C:\Documents and Settings\Owner\cbproject\sandbox\windows\Debug_Bui ld>sandbox lipsum.txt out.txt 5
C:\Documents and Settings\Owner\cbproject\sandbox\windows\Debug_Bui ld>more out.txt
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aenean vel nisl ullamcorper lectus fringilla vestibulum.
Aenean mattis consequat leo.
Praesent in nibh ut tortor cursus sagittis.
Fusce varius lacus et lorem.