Well, you should make sure there's enough room in fname
to store your file name, otherwise you'll almost certainly cause corruption and "blowing up" :-)
For example, the following snippet:
char fname[10];
gets (fname);
will be problematic if you enter more information than fname
can hold. At that point, you're into undefined behaviour territory and anything can happen.
But, because gets
provides no way to limit what the user enters, you should never use it!
A proper, protected, method of user input can be found in this answer.
It uses fgets
since that can limit what the user enters. It also allows for a prompt, provides an error indication if something goes wrong, handles end-of-file correctly, and removes the remainder of any too-large line so that it cannot affect the next input operation.
In fact, I'll copy it here to make this answer self-contained:
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}
You can call it as follows, specifying the buffer and size, and receiving an error indication on return:
// Test program for getLine().
int main (void) {
int rc;
char buff[10];
rc = getLine ("Enter string> ", buff, sizeof(buff));
if (rc == NO_INPUT) {
// Extra NL since my system doesn't output that on EOF.
printf ("\nNo input\n");
return 1;
}
if (rc == TOO_LONG) {
printf ("Input too long [%s]\n", buff);
return 1;
}
printf ("OK [%s]\n", buff);
return 0;
}