-
rename() problem
I'm having a tough time trying to figure out what the heck is wrong with my code.
If anyone would like to help, that'd be cool.
here's my code.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void renamefile( void );
int main()
{
int input;
for( input = 0; input <= 2; input++)
{
printf(">>>> 1. Rename file\n");
printf(">>>> 2. Exit Program\n");
printf("\nEnter selection: ");
scanf("%d", &input);
if( input == 1 )
{
printf("Entering Rename file. . .\n");
renamefile();
if( input == 2 )
{
printf("Exit program...\n");
exit(0);
}
}
}
return input;
}
void renamefile( void )
{
char oldname[80], newname[80];
printf("Enter current filename: ", oldname);
gets(oldname);
printf("Enter new filename: ", newname);
gets(newname);
if( rename( oldname, newname ) == 0)
printf("File %s has been rename to %s.\n", oldname, newname);
else
fprintf(stderr, "Somethings screwed.\n");
}
When it compiles, it's all good and dandy then when I execute it it outputs this
>>>> 1. Rename file
>>>> 2. Exit program
Enter Selection: 1
Entering Rename file. . .
Enter current filename: Enter new filename:
As you can see, it's not exactly doing what i want it to...
Any suggestions?
Thanks
Russ.
-
after each gets() try
fflush(stdin);
-
Actually scanf problem
You're mixing scanf with other input functions.
http://www.eskimo.com/~scs/C-faq/q12.18.html
scanf makes such a mess of the input stream that you have to tidy it up before using some other input function.
This is what you need to add to your code
Code:
scanf("%d", &input);
while ( getchar() != '\n' ) { } /* Add this line of code */
This while loop removes the trailing input characters from the numeric input.
You will also want to start using fgets in place of gets
http://www.eskimo.com/~scs/C-faq/q12.23.html
No doubt some people will tell you to use
fflush( stdin );
but they are wrong, ignore them.
-
>
No doubt some people will tell you to use
fflush( stdin );
but they are wrong, ignore them.
<
hmm....woops.
::edit:: cant believe i didn't see that, just shows waht exp will do for ya. Thank You, Salem.
-
I figured it out with your help, thanks a lot guys. :)
Russ