I have a simple C function where, I have a user supply a path name and the function checks it to see if it is valid file or not.
# 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;
}
Only after running this the file returns as invalid no matter if it is a valid path or not. I have removed the newline
character \n
and replaced it with a null terminator
\0
but, it still doesn't recognize a correct path.
I have very minimal experience with C and I'm not sure where I should be looking to correct this?
EDIT:
These are the compile warnings I received:
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";
^
Again I'm not sure how to correct these "warnings"?
"\n"
and "\0"
are string literals (and "\0"
is a particularly weird string literal, at that). You want to compare to character literals: '\n'
and '\0'
.
You also have a single =
where you want a ==
in the second comparison (the one that should be comparing to '\0'
).
You should read the comp.lang.c
FAQ section 8, Characters and Strings.