Link to home
Start Free TrialLog in
Avatar of lhgarrett
lhgarrett

asked on

replacing strings

What is an easy way to check for the last period in a file path, trucate the extention, and replace it with something else? There may be more than three characters as the extension. The code below just truncates three characters.

For example:
  input file =   C:\My Projects\Input files\myinputfile1.louis.stuff
  output file =  C:\My Projects\Input files\myinputfile1.louis.freq_p2

For example:
  input file =   C:\My Projects\Input files\myinputfile1
  output file =  C:\My Projects\Input files\myinputfile1.freq_p2

void parse_arguments (int num_args, char *arg_array[])
{
   unsigned short BUFFER_LENGTH = 200;

   char FileInput[BUFFER_LENGTH]  = {'\0'};
   char FileOutput[BUFFER_LENGTH] = {'\0'};

   strncpy( FileInput, arg_array[1], BUFFER_LENGTH );

   strncpy(FileOutput, FileInput, (strlen(FileInput) - 3));

   FileOutput[strlen(FileInput) - 3] = '\0';

   strcat(FileOutput, "freq_p2");
}
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of niemeyer
niemeyer

It should work even if the file has no extension at all...

char* rename(char* old_name, char* new_ext)
{
  static char buffer[200],*end,*dot;
  strcpy(buffer,old_name);
  end = buffer;
  while(*end != 0)
    end++;
  dot = end;
  while(*dot != '.' && dot != buffer)
    dot--;
  if(dot == buffer) {
    dot = end;
    *dot = '.';
  }
  dot++;
  while(*new_ext != 0)
    *dot++ = *new_ext++;
  return buffer;
}

int main()
{
  puts(rename("my_file.old","new_ext"));
  return 0;
}
Avatar of lhgarrett

ASKER

> char* rename(char* old_name, char* new_ext)

This looks to be a bit overkill, but thanks.
> strrchr

This works great:

unsigned short length = 0;

if (strrchr(FileInput,'.'))
{
   length = strlen(strrchr(FileInput,'.'));
}

strncpy(FileOutput, FileInput, (strlen(FileInput) - length) );

strcat(FileOutput, BinaryExt);
Yes... but my overkill is a lot faster than your code... :-)