Can anyone help with my do-while statement?
It doesn't work when input file name is blank (empty return).
Code:
if(argc == 1) // 0 & 1; only the program name is input
{
do
{
printf("\n Enter the input file name: ");
fflush(stdin);
gets(fileNameIn);
} while (fileNameIn == NULL);
printf("\n Enter the output file name: ");
fflush(stdin);
gets(fileNameOut);
} ;
Your compiler realizes that you are brutalizing the C language, so it refuses to allow the code to work properly. Either that, or you're just doing some things horribly wrong. In the event it is the latter, allow me to help:
Code:
/**
*** Point #1: 'main' returns an 'int'. Period.
*** Anyone who tells you otherwise is wrong.
*** End of discussion.
***/
int main( int argc, char *argv[])
{
/**
*** Slight adjustment on your declaration. You can
*** just use 0 here, or '\0', and while "\0" may work,
*** it isn't the preferred way of doing it. Just remember
*** this: single quotes for a single character.
**/
char fileNameIn[20] ={0};
char fileNameOut[20] = {0};
/**
*** This will work also:
**/
if( argc < 2 )
{
do
{
printf("\n Enter the input file name: ");
/**
*** 'fflush( inputStreamHere )' will not work the same
*** on every compiler. Just because it works on one,
*** doesn't mean it will work on another. It is not ANSI
*** defined.
***
*** Never, ever, ever, use 'gets'. Use 'fgets' instead.
*** 'gets' is unsafe because i could enter 80 characers in
*** your buffer and trash your program.
***
*** 'fileNameIn' will never equal NULL. fileNameIn[0] may
*** be null, but that 'fileNameIn' still points to allocated
*** memory. It is not a NULL poitner.
**/
} while( fgets( fileNameIn, 20, stdin ) == NULL );
/**
*** The ; you had here is not needed. Neither is this gets for
*** the input file name. See below.
**/
}
if ( argc == 2 || fileNameOut[0] == NULL )
{
printf("\n Please enter output file name: ");
fgets( fileOutName, 20, stdin );
strncpy( fileNameIn, argv[1], 20 );
fileNameIn[19] = NULL;
}
/**
*** I prefer strncpy over strcpy due to it being safer.
*** I manually make sure the last element is NULL.
if ( argc == 3 )
{
strncpy( fileNameIn, argv[1], 20 );
strncpy( fileNameOut, argv[2], 20 );
fileNameIn[19] = fileNameOut[19] = NULL;
}
printf("\n argc = %d\n", argc);
printf(" Program name = %s\n", argv[0]);
printf(" file name in = %s\n", fileNameIn);
printf(" file name out = %s\n", fileNameOut);
/**
*** Since 'main' always returns an int, we return one.
**/
return 0;
}
Try that on for size. If you've any more questions, fire away.
Quzah.