Thread: Setting up the name of a file in the executable directory

  1. #1
    Registered User
    Join Date
    Sep 2015
    Posts
    13

    Setting up the name of a file in the executable directory

    I have to create a buffer to hold the the name of a license file which is in the executable directory. This is my klugy solution (I'm not a C programmer):

    Code:
      char buffer[MAX_PATH] = "";
      GetModuleFileName(NULL, buffer, MAX_PATH);
      int len = (int) strlen(buffer);
      buffer[len-7] = '\0';
      strcat(buffer,"license.lic");
    Note I know the name of the executable is net.exe - 7 chars, so I'm cheating.

    Firstly is this code safe? I got a compiler warning about using strcat saying I should use strcat_s, but I couldn't get that working.

    Secondly how do I get the correct length of the executable name?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,489
    > Firstly is this code safe?
    No.
    - you don't check GetModuleFileName for success (I really hope this code goes nowhere near XP, which broke GetModuleFileName)
    - len is unnecessarily an int - make it size_t
    - len-7 risks potential underflow if the (ab)user can manipulate the name of your program
    - strcat risks potential overflow for the same reason.

    > Note I know the name of the executable is net.exe
    Today maybe, but what if some wally moves your program to C:\x.exe ?

    > I got a compiler warning about using strcat saying I should use strcat_s, but I couldn't get that working.
    That doesn't tell us much. You need to show your attempt if you want diagnosis as to how you got it wrong.

    > Secondly how do I get the correct length of the executable name?
    You could use p = strrchr(buff,'\\');
    If successful, p will point to the last '\' in buff.



    If you just want to get going and ignore issues, then put this on line 1 of your code.
    Code:
    #define _CRT_SECURE_NO_DEPRECATE
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 04-30-2010, 06:13 PM
  2. Loading a DLL that is not in the same directory as the executable
    By starcatcher in forum Windows Programming
    Replies: 10
    Last Post: 12-13-2008, 07:05 AM
  3. Replies: 9
    Last Post: 03-03-2006, 10:11 PM
  4. Executable file
    By Mak in forum Linux Programming
    Replies: 2
    Last Post: 03-27-2004, 03:16 AM
  5. Executable File
    By Drew in forum C++ Programming
    Replies: 5
    Last Post: 08-29-2003, 06:08 PM

Tags for this Thread