I read the other articles for finding the file extension from a filename in C and I’ve tried them but the problem is that they don’t work correctly.
This is my code :
void optionOne()
{
char filenameSrc[101],filenameDest[101];
strcpy(filenameSrc,"");
do
{
printf("Enter source filename (*.c) : ");
scanf("%s",filenameSrc);
}while (check_file_ext(filenameSrc) != 0);
fflush(stdout);
printf("Enter destination filename : ");
scanf("%s",&filenameDest);
char line[80];
FILE* fp = fopen("data.inp","r");
while(fgets(line,sizeof(line),fp))
{
// do something
}
fclose(fp);
}
and the function check_file_ext :
const char *get_file_ext(const char *filename)
{
const char *dot = strrchr(filename, '.');
if(!dot || dot == filename) return "";
return dot + 1;
}
int check_file_ext(const char* filename)
{
return strcmp(get_file_ext(filename),"c") == 0;
}
The problem is in the check method for the file extension?
Could you tell me where is the problem in the code?
Don’t return
"", return a pointer to'\0'byte instead:Note: it ncludes
.in the extension for consistency.Output
Reverse condition:
do{ ... }while(strcmp(get_file_ext(filename), ".c") != 0);