delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/01/26/21:00:22

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Plz help newbie on file i/o
Date: Sun, 26 Jan 1997 13:58:59 -0800
Organization: Two pounds of chaos and a pinch of salt
Lines: 69
Message-ID: <32EBD3A3.7012@cs.com>
References: <01bc0b81$9380a6a0$e8718ea1 AT a>
Reply-To: fighteer AT cs DOT com
NNTP-Posting-Host: ppp211.cs.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

LSC wrote:
> 
>   Hi, I'm new to DJGPP and C/C++. I needs to write an text editor that
> needs file I/O. Can someone please post a simple program that reads a file
> and write to a file. Any help would be greatly appreciated.

The following simple program copies one file to another using binary
mode.  I strongly suggest you look up all the functions I use in the
libc docs that accompany the djgpp distribution.  Also, find a good
textbook on C programming.  :)

#include <stdio.h>

#define BUF_SIZE	16384

int main( int argc, char **argv )
{
    char buffer[BUF_SIZE];
    char *source, *dest;
    FILE *fp_in, *fp_out;
    int n;

    if ( argc < 3 )
    {
        fprintf( stderr, "Syntax:  %s <source> <dest>\n", argv[0] );
        exit( 1 );
    }

    source = argv[1];
    dest = argv[2];

    if ( ( fp_in = fopen( source, "rb" ) ) == NULL )
    {
        perror( source );
        exit( 1 );
    }
    if ( ( fp_out = fopen( dest, "wb" ) ) == NULL )
    {
        perror( dest );
        exit( 1 );
    }

    while ( ( n = fread( buffer, 1, sizeof(buffer), fp_in ) ) > 0 )
        if ( fwrite( buffer, 1, n, fp_out ) < 0 )
	{
	    perror( dest );
	    fclose( fp_in );
	    fclose( fp_out );
	    exit( 1 );
	}

    fclose( fp_in );
    fclose( fp_out );

    printf( "1 file copied.\n" );
    return 0;
}

-- 
John M. Aldrich <fighteer AT cs DOT com>                      

* Anything that happens, happens.
* Anything that, in happening, causes something else to happen,
  causes something else to happen.
* Anything that, in happening, causes itself to happen again, happens
  again.
* It doesn't necessarily do it in chronological order, though.
 
                                       --- Douglas Adams

- Raw text -


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