public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* (1) C and C++ (2) gets() and fgets()
@ 2011-12-26 20:22 Matthew D. Gutchess
  2011-12-26 21:42 ` Sam Varshavchik
  0 siblings, 1 reply; 2+ messages in thread
From: Matthew D. Gutchess @ 2011-12-26 20:22 UTC (permalink / raw)
  To: gcc-help

Hi, 
    My goal is to learn how to write windows-type programs in C++, so to update my programming skills, I am compiling and running sample C and C++ programs.  

    (1) C versus C++.  The ".h" is not used in C++ include files, correct?  I assume that C and C++ object files can be linked into an executable, but are C and C++ incompatible with each other?  Should one use C or C++ or are the two dialects compatible?  What can one accomplish in C++ that cannot be accomplished in C?  

    (2) Man pages state that gets() is "dangerous" because it can be used to purposely cause buffer overflows and recommend using fgets().  gets() accepts input from stdin, but fgets() accepts input from stream.  

For example, how would the program below be modified to use fgets() instead of gets()?:
/*

 * L I S T _ 3

 *

 * Display the contents of an ASCII text file

 * file on the user's screen.

 *

 */



#include <stdio.h>



#define MAXPATH 64

#define MAXLINE 256



int

main(void)

{

	int ch;                 /* input character */

	FILE *fp;               /* file pointer */

	char pathname[MAXPATH]; /* filename buffer */

	char line[MAXLINE];     /* line buffer for fgets() */



	/*

	 * Prompt the user for a filename and read it.

	 */

	printf("Filename: ");

	gets(pathname);

	if (*pathname == '\0')

           {

                printf("\n\n File not found. \n");

		return (0);

           }

        else

           {

  	    /*

	     * Open the named file for reading.

	     */

	    fp = fopen(pathname, "r");



	    /*

	     * Read the contents of the file and display it

	     * a line at a time as it is read.

	     */

	    while (fgets(line, MAXLINE, fp) != NULL)

		fputs(line, stdout);



	    /*

	     * Close the file.

	     */

	    fclose(fp);

            }

        

	return (0);

}

^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2011-12-26 20:22 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2011-12-26 20:22 (1) C and C++ (2) gets() and fgets() Matthew D. Gutchess
2011-12-26 21:42 ` Sam Varshavchik

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).