Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing tabs in character array with spaces in C

Tags:

arrays

c

file-io

I made a small C program so that I can clear out all of the tabs from my homework automatically and replace them with 4 spaces. I find the tabs in a character array with the following function -

char * tabFinder(char * fileString,int * nonNullItems)
{
    int numElements = 0;
    int run = 1;
    while(run)
    {
        while(fileString[numElements] != '\t' &&
              fileString[numElements] != '\0')
            numElements++;

        if(fileString[numElements] == '\t')
        {
            fileString = tabDestroyer(fileString,&numElements,nonNullItems);
            *nonNullItems = *nonNullItems + 3;
        } else run = 0;

    }
    fileString[*nonNullItems + 1] = '\0';
    return fileString;
}

Every time a tab is found, it passes it to my replacer function tabDestroyer which looks like this -

char * tabDestroyer(char * fileString, int * indexOfTab,int * currentItems)
{
    char * tempString = malloc(*currentItems + 3);
    int index = 0,tempIndex;;

    while(index < *indexOfTab)
    {
        tempString[index] = fileString[index];
        index++;
    }   

    tempString[index++] = " ";

    tempString[index++] = " ";

    tempString[index++] = " ";

    tempString[index++] = " ";


    *currentItems = *currentItems + 3;

    while(index < *currentItems)
    {
        tempString[index] = fileString[index - 3];
        index++;
    }

    return tempString;
}

It successfully finds and replaces the tabs, but I'm having an issue with what it's replacing the tabs with.

For instance, a string read in from a file looking like this(pretend there's a tab at the front) -

        int i, numHuge, rowCount = 0;

Turns into this -

FFFFint i, numHuge, rowCount = 0;

Any ideas why this could be?

like image 711
Jon Avatar asked Nov 25 '25 17:11

Jon


1 Answers

char * tempString;
tempString[index++] = " ";
                      ^ ^

For starters, using single quotes, i.e. ' '.

like image 76
cnicutar Avatar answered Nov 27 '25 06:11

cnicutar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!