-
get file extension
Hello
in my program i go to specific directry .From this directry i read files names and write them in the console BUT my problem is the following i want to display the names of files has (s) extension like the follwoing :
a.s
b.s
a.txt
now my approach to display files names which has extension s
a
b
so i did already program display all files in directry BUT
1 . how i can chech for file extension
2.how i can display the file name without its extension
Thanks a lot
-
You could use the library function strrchr() to get a pointer to the '.'. The characters after that will be the extension and the characters before will be the filename.
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char* ext;
char* p;
char fullname []="file.txt";
ext = strchr(fullname,'.');
printf("extension - %s\nfilename - ",ext+1);
for(p=fullname;p!=ext;p++)
{
printf("%c",*p);
}
printf("\n");
}
-
/******
The following code should work for all combinations of file names you might have.
The different types are:
c:\user\myfile.dat
testfile.dat
data
c:\thisfile
Just call the function StripFileName with your file name. The parsed name is returned in NewFileName.
****/
Code:
#include <stdio.h>
#include <string.h>
/*************** PROTOTYPES ************************/
static void StripFileName(char *FileName, char *NewFileName);
/**************************************************/
int main(int argc, char* argv[])
{
char FileName[31];
char NewFileName[31];
strcpy(FileName, "c:\\user\\myfile.dat");
StripFileName(FileName, NewFileName);
printf("(%s)\n", NewFileName);
strcpy(FileName, "testfile.dat");
StripFileName(FileName, NewFileName);
printf("(%s)\n", NewFileName);
strcpy(FileName, "data");
StripFileName(FileName, NewFileName);
printf("(%s)\n", NewFileName);
strcpy(FileName, "c:\\thisfile");
StripFileName(FileName, NewFileName);
printf("(%s)\n", NewFileName);
return 0;
}
static void
StripFileName(char *FileName, char *NewFileName)
{
int PLocation;
int i;
int x;
i = strlen(FileName) - 1;
/* LOOK FOR THE PERIOD OR THE BEGINNING OF THE FILE NAME */
while (i && FileName[i] != '.')
{
i--;
}
/* IF I IS > 0, THE FILE NAME HAS A PERIOD */
if (i)
{
PLocation = i;
}
else
{
/* NO PERIOD, SO COPY TO THE END OF THE FILE NAME */
PLocation = strlen(FileName);
/* RESET i TO LOOK FOR THE FIRST PATH NAME SEPARATOR, SINCE i WENT TO ZERO LOOKING FOR A PERIOD */
i = strlen(FileName) - 1;
}
/* SEARCH FOR THE FIRST PATH NAME SEPARATOR, IF THERE IS ONE */
while (i && FileName[i] != '\\')
{
if (FileName[i] != '\\')
i--;
}
/* IF THERE IS A SEPARATOR, WE NEED TO GO FORWARD 1 CHARACTER */
if (FileName[i] == '\\')
i++;
x = 0;
/* COPY FROM THE SEPARATOR (OR THE BEGINNING OF THE FILE NAME IF NO SEPARATOR) TO LOCATION OF THE PERIOD */
while (i < PLocation)
{
NewFileName[x] = FileName[i];
x++;
i++;
}
/* PLACE A NULL AT THE END WHEN WE'RE DONE COPYING */
NewFileName[x] = '\0';
}
-
Thaaaaaanks a lot for support