我有一個簡單的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";
^
再次聲明,我不知道如何糾正這些「警告」?
編譯時啓用警告。你會有不少的。在你修好之後回來。 – 2013-05-28 20:04:46
@ H2CO3我發佈了編譯警告,但是,我不知道如何糾正它們。 – tijko
嘗試單引號... –