我有一个简单的 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
并将其替换为 anull 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";
^
同样,我不确定如何纠正这些“警告”?