cvs.gedasymbols.org/archives/browse.cgi   search  
Mail Archives: djgpp/1998/02/09/00:00:53

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Randon Function
Date: Sun, 08 Feb 1998 23:59:47 -0500
Organization: Two pounds of chaos and a pinch of salt.
Lines: 63
Message-ID: <34DE8D3D.115E@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>
NNTP-Posting-Host: ppp216.cs.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Matt Kris wrote:
> 
> How do I read different lines of a text file?  If I knew that i could do the
> rest easily.

This is not relevant to DJGPP, but I'll answer anyway.  When you read a
text file, each line ends with a '\n' character (newline).  Reading
individual lines is as simple as reading up to the '\n' as many times as
needed to get to the line you want.  The function fgets() is useful for
this because it reads an individual line and stores it in a string.  To
go back to the beginning of the file, use fseek( fp, 0, SEEK_SET );.  To
make sure you don't read past the end-of-file, test for the success of
each read operation.

Sample code:

/* input:  buffer, # of chars in buffer, # of line to seek, and file 
 * pointer to read from (must be opened in text mode).
 * output:  if successful, buffer contains line read, and returned
 * pointer points to start of buffer.  if unsuccessful (EOF found
 * before specified line), returned pointer is NULL.
 */
char * read_one_line( char *buf, int len, int seek_line, FILE *fp )
{
    char *line;
    int count;

    /* create local buffer to hold input */
    line = (char *) malloc( len * sizeof(char) );

    /* go to start of file */
    fseek( fp, 0, SEEK_SET );

    /* Read each line from file, stopping when there is no more to
     * read or seek_line is reached.  If a line is longer than
     * the size of the buffer, will get last 'len' chars. 
     */
    for ( count = 0; count < seek_line &&
                     fgets( line, len, fp ) != NULL; )
        if ( line[strlen( line ) - 1] == '\n' )
            count++;

    if ( count == seek_line )
    {
        strncpy( buf, line, len - 1 );
        buf[len - 1] = '\0';
        free( line );
        return buf;
    }
    else
    {
        free( line );
        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