• C

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");
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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;
  end = buffer;
  while(*end != 0)
  dot = end;
  while(*dot != '.' && dot != buffer)
  if(dot == buffer) {
    dot = end;
    *dot = '.';
  while(*new_ext != 0)
    *dot++ = *new_ext++;
  return buffer;

int main()
  return 0;
lhgarrettAuthor Commented:
> char* rename(char* old_name, char* new_ext)

This looks to be a bit overkill, but thanks.
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);
Yes... but my overkill is a lot faster than your code... :-)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.