How to Get Current Directory in 10 Programming Languages
In: C++, C, Lua, Java, Bash, JavaScript, Python, PHP, Golang and Ruby.
Algumas tarefas básicas muitas vezes servem para memorizarmos conceitos fundamentais.
Some basic tasks often serve to memorize fundamental concepts.
So, in this article today we will see how to get the current directory in 10 different programming languages. Among them: C++, C, Lua, Java, Bash, JavaScript, Python, PHP, Golang e Ruby.
All were used as simply as possible and in a modern way. It will also serve to review how to concatenate and basic syntax.
In each code there will also be a comment according to the language to compile and/or interpret via the command line.
C++
#include <iostream>
#include <filesystem>
int main(){
std::cout << "The current directory is: "
<< std::filesystem::current_path() << '\n';
return 0;
}
// g++ -std=c++17 current.cpp && ./a.out
C
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
int main() {
char cwd[PATH_MAX];
getcwd(cwd, sizeof(cwd));
printf("The current directory is: %s\n", cwd);
return 0;
}
// gcc current.c && ./a.out
Lua
print("The current directory is: " .. os.getenv("PWD"))
--lua current.lua
Java
public class current {
public static void main(String[] args) {
System.out.println("The current directory is: " + System.getProperty("user.dir"));
}
}
// javac current.java && java current
Bash
echo "The current directory is: ${PWD}"
# bash current.sh
JavaScript
console.log("The current directory is: " + process.cwd() )
// node current.js
Python
import os
print("The current directory is: " + os.getcwd())
# python current.py
PHP
<?php echo "The current directory is: " . getcwd() . "\n";
# php current.php
Golang
package main
import (
"fmt"
"os"
)
func main(){
dir,err := os.Getwd() ; _ = err
fmt.Println("The current directory is: " + dir)
}
// go build current.go && ./current
Ruby
puts "The current directory is: " + Dir.pwd
# ruby current.rb
cpp clanguage lua bash javascript python php go ruby
Comments