Kaidul
Kaidul

Reputation: 15875

Rename filename C++

I am trying to replace whitespace characters with underscore and rename file names in a directory. Everything seems well but the rename operation is not renaming the files.

DIR *dir;
char *directoryPath = "E:\\markdown-here.wiki\\LeetCode_problems_solution\\";
struct dirent *ent;
if ((dir = opendir (directoryPath)) != NULL) {
    while ((ent = readdir (dir)) != NULL) {
        char *filename;
        for(int i = 0; i < strlen(ent->d_name); ++i) {
            if(ent->d_name[i] == ' ')
                filename[i] = '_';
            else filename[i] = ent->d_name[i];
        }
        filename[strlen(ent->d_name)] = '\0';

        // output: Error renaming file: No such file or directory
        int result = rename(ent->d_name, filename);
        if(result == 0) puts ( "File successfully renamed" );
        else perror( "Error renaming file" );

        // this works
        printf ("%s, %s\n", ent->d_name, filename); // foo bar, foo_bar
    }
    closedir (dir);
} else {
    /* could not open directory */
    perror ("");
    return EXIT_FAILURE;
} 

What's wrong here?

Upvotes: 0

Views: 1588

Answers (1)

R Sahu
R Sahu

Reputation: 206577

The main problem is that you have:

    char *filename;

but have not allocated memory for it. You are running into undefined behavior.

Try

    char filename[1000]; // Or something large enough.

Also, the way you are using rename, it will work only if the current directory is set to directoryPath Otherwise, ent->d_name is not a valid file name.

You can chdir to directoryPath or use the absolute path in the arguments to rename.

Upvotes: 2

Related Questions