1

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?

3
  • It would be easier to answer if you described what the problem actually was. Commented Jan 29, 2012 at 9:08
  • I really don't know what was the problem. I used a header file with defined functions and the two functions check_file_ext and get_file_ext was declared there in the header file. When I moved them in the main c file the problem disappeared. Commented Jan 29, 2012 at 9:11
  • The condition for your first while loop looks backward (loops until the file extension is not valid). Commented Jan 29, 2012 at 9:13

1 Answer 1

2

Don't return "", return a pointer to '\0' byte instead:

// gcc -std=c99 #include <stdio.h> #include <string.h> static const char* get_file_ext(const char *filename) { const char *ext = strrchr(filename, '.'); return (ext && ext != filename) ? ext : (filename + strlen(filename)); } int main() { char *files[] = {"a.c", ".a", "a", NULL }; for (char** f = files; *f != NULL; ++f) printf("ext: '%s'\n", get_file_ext(*f)); } 

Note: it ncludes . in the extension for consistency.

Output

ext: '.c' ext: '' ext: '' 

Reverse condition: do{ ... }while(strcmp(get_file_ext(filename), ".c") != 0);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.