まあ、fname
ファイル名を保存するのに十分なスペースがあることを確認する必要があります。そうしないと、ほぼ確実に破損や「爆発」が発生します:-)
たとえば、次のスニペットです。
char fname[10];
gets (fname);
保持できる以上の情報を入力すると問題が発生fname
します。その時点で、あなたは未定義の行動の領域に入り、何でも起こり得る.
ただし、gets
ユーザーが入力する内容を制限する方法がないため、絶対に使用しないでください。
ユーザー入力の適切で保護された方法は、この回答にあります。
fgets
ユーザーが入力する内容を制限できるため、使用します。また、プロンプトを許可し、何か問題が発生した場合にエラーを表示し、ファイルの終わりを正しく処理し、大きすぎる行の残りを削除して、次の入力操作に影響を与えないようにします。
実際、ここにコピーして、この回答を自己完結型にします。
#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;
}
次のように呼び出して、バッファーとサイズを指定し、戻り時にエラー表示を受け取ることができます。
// 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;
}