Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #105 Current executable name

Assign to the string s the name of the currently executing program (but not its full path).

import std.path;
void main(string[] args) {
    string s = args[0].baseName;
}
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Directories; use Ada.Directories;
S : String := (Simple_Name (Command_Name));
#include <string.h>
#ifdef _WIN32
#define PATH_SEP '\\'
#else
#define PATH_SEP '/'
#endif

int main(int argc, char* argv[])
{
    char *s = strchr(argv[0], PATH_SEP);
    s = s ? s + 1 : argv[0];

    return 0;
}
#include <iostream>
#include <filesystem>

int main(int argc, char* argv[])
{
    std::cout << std::filesystem::path(argv[0]).filename() << '\n';
}
using System;
using System.IO;
var path=Environment.CommandLine;
var s=Path.GetFileName(path);
import 'dart:io';
var s = File(Platform.resolvedExecutable).uri.pathSegments.last;
program p
implicit none
character(len=:),allocatable :: s
integer                      :: stat,l,i,j,k
 call get_command_argument (0,length=l)
 allocate(character(len=l) :: s)
 call get_command_argument (0,s,status=stat)
 if (stat == 0) then
  i=index(s,'/',back=.true.)
  j=index(s,'\',back=.true.)
  k=max(i,j)
  if(k.ne.0)s=s(k+1:)
  print *, "The program's name is " // trim (s)
 endif
end program p
import "os"
import "path/filepath"
path := os.Args[0]
s = filepath.Base(path)
import (
  "os"
  "path/filepath"
)
path, err := os.Executable()
if err != nil {
  panic(err)
}
s = filepath.Base(path)
import System.Environment
s <- getProgName
var s = process.argv0;
String s = System.getProperty("sun.java.command");
s = arg[0]
$s = $_SERVER['PHP_SELF'];
s := ExtractFileName(ParamStr(0));
my $s = $0;
import sys
s = sys.argv[0]
s = $0
s = __FILE__
let s = std::env::current_exe()
    .expect("Can't get the exec path")
    .file_name()
    .expect("Can't get the exec name")
    .to_string_lossy()
    .into_owned();
fn get_exec_name() -> Option<String> {
    std::env::current_exe()
        .ok()
        .and_then(|pb| pb.file_name().map(|s| s.to_os_string()))
        .and_then(|s| s.into_string().ok())
}

fn main() -> () {
    let s = get_exec_name().unwrap();
    println!("{}", s);
}

New implementation...
< >
programming-idioms.org