www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/02/10/22:35:11

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Randon Function
Date: Tue, 10 Feb 1998 19:03:32 -0500
Organization: Two pounds of chaos and a pinch of salt.
Lines: 71
Message-ID: <34E0EAD4.562F@cs.com>
References: <6bgtsb$h8o AT alpha DOT delta DOT edu> <6bgvt1$ruu AT freenet-news DOT carleton DOT ca> <6blsh6$4ik AT alpha DOT delta DOT edu> <34DE8D3D DOT 115E AT cs DOT com> <34dfe7b8 DOT 6111175 AT news DOT netaccess DOT co DOT nz>
NNTP-Posting-Host: ppp224.cs.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019