Mail Archives: djgpp/1998/02/10/22:35:11
Richard Chappell wrote:
>
> >char * read_one_line( char *buf, int len, int seek_line, FILE *fp )
> >{
> [snip]
> >}
>
> So if I wanted to use this function in a program, would I have:
>
> char *mypc;
> mypc=read_one_line(&mypc, myLenWanted,myLineWanted,"data.txt");
This won't even have a ghost of a chance of working. Problems:
1) You don't allocate any space for the buffer, nor do you initialize it
to anything. This is guaranteed to cause a crash.
2) "data.txt", as Eli pointed out, is not a file pointer; it's a string.
> If I've done this wrongly (which I probably have because I don't
> really know anything about file i/o) please tell me what I did wrong,
> and how to fix it !!
The code I used to test the above function is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
/* read_one_line function from above */
int main( int argc, char *argv[] )
{
char line[10000];
FILE *fp;
int n;
if ( argc < 3 )
exit( 1 );
if ( ( fp = fopen( argv[1], "r" ) ) == NULL )
{
perror( argv[1] );
exit( 1 );
}
n = atoi( argv[2] );
if ( read_one_line( line, 10000, n, fp ) == NULL )
printf( "Line not found.\n" );
else
printf( line );
fclose( fp );
return 0;
}
This program is invoked with "getxline filename count", where filename
is the name of the file, and count is a number indicating which line to
read. I named the program 'getxline'. Note: the code doesn't check
for the count to be a valid number; if it's anything else, the code will
return garbage in the buffer. This is a bug in my function, btw; it
should detect seek_line == 0 and return NULL.
--
---------------------------------------------------------------------
| John M. Aldrich | "Always listen to experts. They'll |
| aka Fighteer I | tell you what can't be done, and why.|
| mailto:fighteer AT cs DOT com | Then do it." |
| http://www.cs.com/fighteer/| - Lazarus Long |
---------------------------------------------------------------------
- Raw text -