change space to underscore in filename using C
Although this indeed does something similar to your goal, here are some criticisms / improvements:


There's absolutely no need to take a copy of the original filename.
If you meet an error condition, return 1 (or better EXIT_FAILURE from stdlib.h), so scripts calling your tool get a chance to detect the error.
Use functions; this helps your code to keep structure
Your tool will not work correctly for filenames with paths, so better search from the end and stop replacing when you hit a path separator character.
When iterating through a string, it's often easier to just use pointers instead of array indexing.


I'd suggest something like this:

#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

#ifdef _WIN32
#define isPathSep(x) ((x) == '\\' || (x) == '/')
#else
#define isPathSep(x) ((x) == '/')
#endif

char *sanitizeFileName(const char *filename)
{
    size_t namelen = strlen(filename);

    char *sanitized = malloc(namelen + 1);
    if (!sanitized)
    {
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    strcpy(sanitized, filename);

    char *p = sanitized + namelen - 1;
    while (p &gt;= sanitized)
    {
        if (isPathSep(*p)) break;
        if (*p == ' ') *p = '_';
        --p;
    }

    return sanitized;
}

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s [filename]\n", argv[0]);
        return EXIT_FAILURE;
    }

    char *safename = sanitizeFileName(argv[1]);

    // instead of rename(), for demonstration:
    printf("%s -&gt; %s\n", argv[1], safename);

    free(safename);

    return EXIT_SUCCESS;
}