Monday, July 23, 2012

making my own strcat() in C

As an exercise, I made my own strcat() function in C:

https://gist.github.com/3164052 for the pretty version.


#include <stdio.h>
#include <string.h>
#define STRINGSIZE 80

int cat(char *a, const char* b, const size_t max_size)
{  
    //puts("FUNCTION BEGIN");
    size_t size = strlen(a);
    a += size;
    while (*b)
    {
        if (size >= max_size)
        {  
            *a = '\0';
            printf("ERROR: function cat() has run past max_size: size = %lu\n", size);
            return -1;  // I feel like I should undo the changes
                        // since I'm returning an error.
        }
        *a++ = *b++;
        size++;
    }
    *a = '\0';
    //puts("FUNCTION FINISHED");
    return 0;
}

int main()
{
    char strA[STRINGSIZE] = "I am a small cat ";
    char strB[STRINGSIZE] = "with whiskers who likes milk.";
    printf("A: '%s'\nB: '%s'\n", strA, strB);
    puts("-= Let's call cat() =-");
    int result = cat(strA, strB, STRINGSIZE);
    if (result == -1)
        printf("main() - ERROR in function cat(): -1\n");
    printf("A: '%s'\nB: '%s'\n", strA, strB);
    printf("cat() returned: '%d'\n", result);
    return 0;
}



Sunday, July 15, 2012

Strings, Arrays, Pointers, and searching in C

After a bout of wrist pain, I'm strating to slowly ease back into programming.  Here is some C code to search through strings for words in sys args, and highlight the found words with brackets.: