1

私は単純な C 関数を持っています。ユーザーにパス名を指定させると、関数はそれが有効なファイルかどうかをチェックします。

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

int main(void) {

    char  cFileChoice[256];
    FILE * rInputFile;
    unsigned int cFileLength;

    printf("\nPlease supply a valid file path to read...\n");

    fgets(cFileChoice, 255, stdin);
    cFileLength = strlen(cFileChoice) - 1;

    if (cFileChoice[cFileLength] == "\n") {
        cFileChoice[cFileLength] = "\0";
    }
    rInputFile = fopen(cFileChoice, "r");
    if (rInputFile != NULL) {
        printf("Enter 'c' to count consonants or enter 'v' for vowels: ");
    }
    else {
        printf("Not a valid file\n");
    }
    return 0;
}

これを実行した後でのみ、有効なパスであるかどうかに関係なく、ファイルは無効として返されます。newline文字を削除して\nに置き換えましたnull terminator \0が、それでも正しいパスが認識されません。

私は C の経験がほとんどなく、これを修正するためにどこを見ればよいかわかりません。

編集:

これらは私が受け取ったコンパイル警告です:

test.c: In function ‘main’:
test.c:15:34: warning: comparison between pointer and integer [enabled by default]
     if (cFileChoice[cFileLength] == "\n") {
                                  ^
test.c:16:34: warning: assignment makes integer from pointer without a cast [enabled by default]
         cFileChoice[cFileLength] = "\0";
                              ^

繰り返しますが、これらの「警告」を修正する方法がわかりませんか?

4

1 に答える 1

3

"\n""\0"は文字列リテラルです ("\0"特に奇妙な文字列リテラルです)。文字リテラルと比較したい:'\n''\0'.

また、2 番目の比較 ( と比較する必要があるもの) で が必要な場所が 1 つ=あります。=='\0'

comp.lang.cFAQ セクション 8、Characters and Stringsを読む必要があります。

于 2013-05-28T20:11:20.567 に答える