Demo entry 2842091

dsa

   

Submitted by asd on Oct 11, 2015 at 22:05
Language: C. Code size: 2.4 kB.

#include <stdio.h>
#include <stdlib.h>

/* Parameters:
 *     FILE *fp --------- The stream to read from.
 *     char delimeter --- The character to read up until (to read an entire line, 
 *                        pass '\n' as this value).
 *     int size -- The initial size of the malloc()'d buffer.
 *                        For example, if you expect a name inputted, specify this
 *                        value as around 30 to minimize reallocs. If you expect a
 *                        long sentance from a file, you may want to increase this value.
 * 
 * Reads any length string from 'FILE *fp' until 'char delimeter' is encountered. 
 * 'int size' is the initial size of the memory buffer. Whenever the memory
 * is filled up, it is realloced() to a new buffer of double the size.
 * At the end, a null terminating byte is added and the string is realloced() again
 * to free any unused memory.
 * 
 * Returns: A pointer to the string read, excluding the delimiter.
 */
char *getDelimiter(FILE *fp, char delimiter, int size);

int main(){
    
    char *line;
    
    printf("Enter a line: ");
    line = getDelimiter(stdin, '\n', 50);
    
    printf("You entered: %s\n", line);
    
    free(line);
    
    return 0;
}

char *getDelimiter(FILE *fp, char delimiter, int size){
    char *string;  /* string to return */
    int i;         /* Index into string. */
    int c;         /* For fgetc(). */
    
    string = malloc(size);
    if(string == NULL){
        return NULL;
    }
    
	i = 0;
    c = fgetc(fp);
    while(c != delimiter){
        /* Reallocate memory if needed. */
        if(i == size){
            size += size;
            string = realloc(string, size);
            if(string == NULL){
                return NULL;
            }
        }
        string[i] = (char)c;
        i++;
        c = fgetc(fp);
    }
    
    /* Allocate space for one more byte (the null terminator). */
    if(i == size){
        string = realloc(string, size+1);
        if(string == NULL){
                return NULL;
        }
        string[i] = '\0';
    }
    else{ /* Add the null terminating character to the end, realloc the string to free any unused memory. */
        string[i] = '\0';
        string = realloc(string, i);
        if(string == NULL){
                return NULL;
        }
    }
    
    return string;
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).