0
votes

I've a program which takes any number of words from the command-line arguments and replaces them with the word 'CENSORED'. I finally have the program working for the first argument passed in, and I am having trouble getting the program to censor all arguments, outputted in just a single string. The program rather functions individually on a given argument and does not take them all into account. How would I modify this?

How does one use/manipulate multiple command-line arguments collectively ?

My code follows.

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

char *replace_str(char *str, char *orig, char *rep, int j, int argc)
{
    static char buffer[4096];
    char *p;

    for ( j = 1; j <= argc; j++ )  
    {

        if(!(p = strstr(str, orig)))  // Check if 'orig' is not in 'str'
        {
            if ( j == argc )    {  return str;  }  // return str once final argument is reached
            else                {  continue;    }  // restart loop with next argument
        }

        strncpy(buffer, str, p-str);  // Copy characters from 'str' start to 'orig' str
        buffer[p-str] = '\0';

        if ( j == argc )        {  return buffer;  }
        else                    {  continue;       }
    }
    sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));
}

int main( int argc, char* argv[] )  //argv: list of arguments; array of char pointers //argc: # of arguments.
{   
    long unsigned int c, i = 0, j = 1;

    char str[4096];

    while ( (c = getchar()) != EOF )
    {
        str[i] = c;  // save input string to variable 'str'
        i++;
    }
    puts(replace_str( str, argv[j], "CENSORED", j, argc ) );

    return 0;
}


i.e. 
$ cat Hello.txt 

Hello, I am me.

$ ./replace Hello me < Hello.txt

CENSORED, I am CENSORED.
1
The j argument is redundant. - emlai
You have two choices, either A) call replace_str multiple times in main before calling puts, or B) pass argc and argv in its entirety to replace_str. - user3386109
the call to getchar() will not input the command line parameters. yet that seems to be what the code is trying to do. - user3629249
this line: 'strncpy(buffer, str, p-str);' will copy 1 character not enough the line should be: 'strncpy(buffer, str, (p-str)+1);' - user3629249

1 Answers

1
votes

Two issues, you are not guaranteeing a null-terminated str and second, you are not iterating over the words on the command line to censor each. Try the following in main after your getchar() loop:

/* null-terminate str */
str[i] = 0;

/* you must check each command line word (i.e. argv[j]) */
for (j = 1; j < argc; j++)
{
    puts(replace_str( str, argv[j], "CENSORED", j, argc ) );
}

Note: that will place each of the CENSORED words on a separate line. As noted in the comments, move puts (or preferably printf) outside the loop to keep on a single line.


Edit

I apologize. You have more issues than stated above. Attempting to check the fix, it became apparent that you would continue to have difficulty parsing the words depending on the order the bad words were entered on the command line.

While it is possible to do the pointer arithmetic to copy/expand/contract the original string regardless of the order the words appear on the command line, it is far easier to simply separate the words provided into an array, and then compare each of the bad words against each word in the original string.

This can be accomplished relatively easily with strtok or strsep. I put together a quick example showing this approach. (note: make a copy of the string before passing to strtok, as it will alter the original). I believe this is what you were attempting to do, but you were stumbling on not having the ability to compare each word (thus your use of strstr to test for a match).

Look over the example and let me know if you have further questions. Note: I replaced your hardcoded 4096 with a SMAX define and provided a word max WMAX for words entered on the command line. Also always initialize your strings/buffers. It will enable you to always be able to easily find the last char in the buffer and ensure the buffer is always null-terminated.

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

#define SMAX 4096
#define WMAX 50

char *replace_str (char *str, char **bad, char *rep)
{
    static char buffer[SMAX] = {0};
    char *p = buffer;
    char *wp = NULL;
    unsigned i = 0;
    unsigned char censored = 0;

    char *str2 = strdup (str);              /* make copy of string for strtok  */
    char *savp = str2;                      /* and save start address to free   */

    if (!(wp = strtok (str2, " ")))         /* get first word in string or bail */
    {
        if (savp) free (savp);        
        return str;
    }

    while (bad[i])                          /* test against each bad word       */
    {
        if (strcmp (wp, bad[i++]) == 0)     /* if matched, copy rep to buffer   */
        {
            memcpy (buffer, rep, strlen (rep));
            censored = 1;
        }
    }

    if (!censored)                          /* if no match, copy original word  */
        memcpy (buffer, wp, strlen (wp));

    while ((wp = strtok (NULL, " ")))       /* repeat for each word in str      */
    {
        i = 0;
        censored = 0;

        memcpy (strchr (buffer, 0), " ", 1);
        p = strchr (buffer, 0);             /* (get address of null-term char)  */

        while (bad[i])
        {
            if (strcmp (wp, bad[i++]) == 0)
            {
                memcpy (p, rep, strlen (rep));
                censored = 1;
            }
        }

        if (!censored)
            memcpy (p, wp, strlen (wp));
    }

    if (savp) free (savp);                  /* free copy of strtok string       */
    return buffer;
}

int main ( int argc, char** argv)
{   
    unsigned int i = 0;
    char str[SMAX] = {0};
    char *badwords[WMAX] = {0};             /* array to hold command line words */

    for (i = 1; i < argc; i++)              /* save command line in array       */
        badwords[i-1] = strdup (argv[i]);

    i = 0;                                  /* print out the censored words     */
    printf ("\nCensor words:");
    while (badwords[i])
        printf (" %s", badwords[i++]);
    printf ("\n\n");

    printf ("Enter string: ");              /* promt to enter string to censor  */

    if (fgets (str, SMAX-1, stdin) == NULL)
    {
        fprintf (stderr, "error: failed to read str from stdin\n");
        return 1;
    }

    str[strlen (str) - 1] = 0;              /* strip linefeed from input str    */

    /* print out censored string */
    printf ("\ncensored str: %s\n\n", replace_str (str, badwords, "CENSORED"));

    i = 0;                                  /* free all allocated memory        */
    while (badwords[i])
        free (badwords[i++]);

    return 0;
}

use/output

./bin/censorw bad realbad

Censor words: bad realbad

Enter string: It is not nice to say bad or realbad words.

censored str: It is not nice to say CENSORED or CENSORED words.