Channels ▼
RSS

Open Source

C Snippet #6



Q: HOW DO I... get a string of any arbitrary length from the console?

A: The ANSI C gets() function is one of those obsolescent functions that is in the standard simply because it would have broken too much existing code to have left it out. The ANSI function fgets() is generally preferable to gets() since it protects against buffer overflow.

The following getstring() function combines the best of both, using dynamic memory allocation to get as large an input string as the user cares to type in. Error trapping is built in as shown. As with all functions that use dynamic memory allocation, once you're through with the returned string, it's a good idea to free() it and return the memory used to the heap.


/*
** GETSTRNG.H - Get a string of unknown length
*/

#ifndef GETSTRNG__H
#define GETSTRNG__H

#include "sniptype.h"   // For NUL

char *getstring(void);

#endif /* GETSTRNG__H */

/* ** GETSTRNG.C -- Demonstration of dynamic memory allocation to ** receive string of unknown length. ** ** Ron Sires 1/31/1989, released to the public domain. ** Bob Stout 3/15/1992, restructure ** Bob Stout 9/27/2009, republish */ #include <stdlib.h> #include <stdio.h> #include "getstrng.h" #define BLOCKSIZ 16 /* ** getstring() - Fetch a string of indeterminant length ** ** Parameters: None ** ** Returns: String or NULL if memory allocation error ** ** Notes: 1 - It is the repsonsibility of the caller to free ** the memory buffer returned by this function! ** 2 - Error/exception handling is the responsibility of ** the caller. ** 3 - If reentrancy isn't required, this may be simpified ** by the use of a static buffer. */ char *getstring(void) { int newchar; size_t i; char *buffer, *newbuf; size_t bufsize; /* Get initial BLOCKSIZ buffer to receive string. */ if ((buffer = (char *) calloc(BLOCKSIZ, sizeof(char))) == NULL) return NULL; bufsize = BLOCKSIZ; /* Get chars from keyboard and put them in buffer. */ for (i = 0; ((newchar = getchar()) != EOF) && (newchar != '\n') && (newchar != '\r'); /* no end term */ ) { buffer[i] = (char) newchar; if (i >= bufsize - 1) /* If buffer is full, resize it. */ { newbuf = (char *) realloc(buffer, bufsize + BLOCKSIZ); if (newbuf == NULL) { free(buffer); return NULL; } buffer = newbuf; bufsize += BLOCKSIZ; } /* Add terminator to partial string & increment pointer */ buffer[++i] = NUL; } return buffer; } #ifdef TEST #include <string.h> int main(void) { char *string; puts("Enter strings of any length or <Enter> to quit\n"); while (1) { string = getstring(); if (NULL == string) puts("\agetstrng() - Insufficient memory"); printf("You entered:\n\"%s\"\n", string); printf("buffer=%p, length=%d\n\n", string, strlen(string)); if (0 == strlen(string)) break; free(string); }; return EXIT_SUCCESS; } #endif /* TEST */


/*
**  SNIPTYPE.H - Include file for SNIPPETS data types and commonly used macros
*/

#ifndef SNIPTYPE__H
#define SNIPTYPE__H

#include <stdlib.h>                             /* For free()           */
#include <string.h>                             /* For NULL & strlen()  */

typedef enum {Error_ = -1, Success_, False_ = 0, True_} Boolean_T;

#ifdef BYTE
 #undef BYTE
#endif
#ifdef WORD
 #undef WORD
#endif
#  ifdef DWORD
 #undef DWORD
#endif
typedef unsigned char  BYTE;
typedef unsigned short WORD;
typedef unsigned long  DWORD;

typedef union {
      signed char       c;
      BYTE              b;
} VAR8_;

typedef union {
      VAR8_             v8[2];
      signed short      s;
      WORD              w;
} VAR16_;

typedef union {
      VAR16_            v16[2];
      signed long       l;
      DWORD             dw;
      float             f;
      void              *p;
} VAR32_;

typedef union {
      VAR32_            v32[2];
      double            d;
} VAR64_;

#define NUL '\0'
#define LAST_CHAR(s) (((char *)s)[strlen(s) - 1])
#define TOBOOL(x) (!(!(x)))
#define FREE(p) (free(p),(p)=NULL)

#endif /* SNIPTYPE__H */

More C Snippets

All the code in C Snippets is either public domain or freeware and may therefore freely be used by the C programming community without restrictions. In most cases, if the original author is someone other than myself he or she will be identified. Thanks to all who have contributed to this collection over the years. I hope Dr. Dobb's readers will find these useful.

--Bob Stout
rbs@snippets.org


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video