change space to underscore in filename using C I have written my first C program that renames spaces in filenames to underscores. I wonder if there is an easier or more efficient way:

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

int main( int argc, char *argv[] ) {

    if ( argc != 2 ) {
        printf("Format is: NoSpace &lt;filename&gt;\n");
        return(0);
    }
    else if ( strstr( argv[1], " ") == NULL) {
        printf("No space character in file: %s\n",argv[1]);
        return(0);
    }

    int filename_size = strlen(argv[1]);
    char file_name_old[filename_size], file_name_new[filename_size];

    strcpy(file_name_old, argv[1]);
    strcpy(file_name_new, argv[1]);

    // ASCII 32 = space; ACII 95 = underscore
    for( int pos = 0; pos &lt; filename_size; pos++) {
        if ( file_name_new[pos] == 32)  {
            file_name_new[pos] = 95;
        }
    }

    rename(file_name_old,file_name_new);
    return(0);
}


Thanks!
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;
}