Changing a dir's name (Should be simple)

Started by
3 comments, last by VanKurt 22 years, 2 months ago
Here''s a little piece of code that has simply the function to rename a directory (From "OriginalName" to "OriginalName2"). BUT the code does NOTHING ! I''ve created the proper directory and entered the right name, but nothing changes. What could be the reason for this ??? Here''s the code:
  
	char buffer[32];

	printf("Enter the directory''s name: ");
	gets( buffer );

	oldname = buffer;
	newname = buffer;
	strcat(newname, "2");

	rename( oldname, newname );
  
thanks, Vk
Advertisement
That code makes a single buffer of 32 characters. It gets a string in it. It then sets two pointers equal to that arrays address. Then it appends two to that address. So, if you enter "fish" as the file you're calling "rename("fish2","fish2")" (yes, it edits both strings). Try printing out newname and oldname as text, you'll see. Also, I don't know if rename does directories, but I'd think it would (but it isn't required since the ANSI standard says nothing about directories).



Edited by - Null and Void on January 31, 2002 8:17:23 AM
Of course it does nothing. You''re making mistakes with your pointers to array.

You can not just assign a pointer to an array of chars, and think you suddenly have 2 strings. It doesn''t work like that. The pointer ends up pointing to the same string.

Effectively, you''re calling rename ("dir2", "dir2").

You need to make another character array for the new name, use strcpy to duplicate the original, then use strcat to append the "2".
Looks to me that your code ends up calling

rename( ''ogname2'', ''ogname2'');

and since the ''ogname2'' directory doesn''t yet exist - nothing happens.

Try using a different buffer for newname, then copy the oldname into it. Then append "2". Then call rename.
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
Allright !

I''ll try that. Thanks very much !!!

(I''m not comfortable with those creepy pointers yet )

This topic is closed to new replies.

Advertisement