/******
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';
}