(1) C and C++ (2) gets() and fgets()

Matthew D. Gutchess mdgutchess1@juno.com
Mon Dec 26 20:22:00 GMT 2011


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);

}



More information about the Gcc-help mailing list