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
- Determining a file's size
- Rounding floating-point values
- Sorting an array of strings
- Computing the wind chill factor
- Timers and default actions
- Querying in a .BAT file, using a timeout default
- Getting a string of arbitrary length
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


