How i can create file filter extension in c. For example i want the fopen function works only with files that ends with .txt extension
How i can create file filter extension in c. For example i want the fopen function works only with files that ends with .txt extension
Then you have to write a function to test if the file extension entered by the user is part of a list of acceptable extensions... and depending on the return value of the function either open the file or tell the user you're not going to.
Have the include file string.h listed in your program.
Have a small char array for the extension. They if the filename you get has a period in it, put the letters after the period, into another small char array. Terminate it with a '\0' char, so it's a legit string.
Now use strcmp(). If ((result=strcmp(array1, array2))==0) then it's a match.
Code:#include <string.h> #define TYPES ".txt.ini.bak.asc" int IsApprovedType(char *str) { if (strstr(str,TYPES)) return 1; return 0; }
That is. until someone types in
mybadfile.txt.exe
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Good point Salem. Be sure to only use letters for you extension string, which are the last letters in the filename.
Might as well just collect them right from the back of the filename, and decrement the index, until you reach the first dot:
filename.txt.exe
Rough code idea:
Code://your program already has the filename in it's array char txt[5]; //for text file extensions+end of string char +1 if(strchr(filename,'.') { i=strlen(filename); j=0; txt[0]='\0'; while(filename[i] !='.') { txt[j]=filename[i]; ++j; --i; } } //now do your strcmp() with txt[]