• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 206
  • Last Modified:

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");
}
0
lhgarrett
Asked:
lhgarrett
  • 2
  • 2
1 Solution
 
ozoCommented:
strrchr
0
 
niemeyerCommented:
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;
}
0
 
lhgarrettAuthor Commented:
> char* rename(char* old_name, char* new_ext)

This looks to be a bit overkill, but thanks.
0
 
lhgarrettAuthor Commented:
> strrchr

This works great:

unsigned short length = 0;

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

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

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

Featured Post

Live webcast with Pinal Dave

Pinal Dave will teach you tricks to help identify the real root cause of database problems rather than red herrings. Attendees will learn scripts that they can use in their environment to immediately figure out their performance Blame Shifters and fix them quickly.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now