0

Cプログラミングの初心者です。読み取り用に開くファイルの名前をユーザーに入力するように求めるプログラムを作成しています。以下に示す私のコードでは、ファイルが開かない場合、またはファイルが存在しない場合にエラーをスローしたいのですが、実行するとコードが爆発し、プログラムを閉じる必要があります (DOS)。

/*ask user for the name of the file*/
  printf("enter file name: ");
  gets(fname);


//Opens the file from where the text will be read. 
fp=fopen(fname, "r");

//Checks if the file us unable to be opened, then it shows the error message 
if (fp == NULL)
    {
     printf("\nError, Unable to open the file for reading\n");
    }

// name.txt ファイルを作成することでこれをテストできます。追加情報が必要な場合はお知らせください。

4

3 に答える 3

5

まあ、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;
}
于 2012-04-11T04:03:16.817 に答える
0

何が欠けているのかわかりませんが、このプログラムは、コマンド ラインで cl.exe を使用してコンパイルおよび実行されます。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    char fname[100];
    FILE* fp;
    memset(fname, 0, 100);
    /*ask user for the name of the file*/
    printf("enter file name: ");
    gets(fname);


    //Opens the file from where the text will be read. 
    fp = fopen(fname, "r");

    //Checks if the file us unable to be opened, then it shows the error message 
    if (fp == NULL)
    {
        printf("\nError, Unable to open the file for reading\n");
    }

}

また、特定のコンパイラ (Microsoft を含む) では、既定のオプションで呼び出された場合、関数の先頭にすべての宣言を配置する必要があることに注意してください。

于 2012-04-11T04:02:22.383 に答える
0

まあ、これは私に起こったことであり、「if」に「else」条件を追加するとうまくいきました。以下にコードを示します。

#include<stdio.h>
#include<conio.h>
#include<string.h>

int  main() 
{

char fname[100];
FILE* fp;
memset(fname, 0, 100);
/*ask user for the name of the file*/
printf("enter file name: ");
gets(fname);

fp = fopen(fname, "r");

//Checks if the file us unable to be opened, then it shows the error message 
if (fp == NULL)
{
    printf("\nError, Unable to open the file for reading\n");
}

else
{
    printf("hello");
}


getch();
}

また、ヘッダー ファイルとして「#include」を追加したことを確認してください。

于 2014-09-20T15:30:17.930 に答える