WeixiangYan/CodeTransOcean huggingface dataset:
Task: JSON





Java: 



grammar JSON ;
@members {
String Indent = "";
}
Number	:	(('0')|('-'? ('1'..'9') ('0'..'9')*)) ('.' ('0'..'9')+)? (('e'|'E') ('+'|'-')? ('0'..'9')+)?;
WS	:	(' ' | '\t' | '\r' |'\n') {skip();};
Tz	:	' ' .. '!' | '#' .. '[' | ']' .. '~';
Control	:	'\\' ('"'|'\\'|'/'|'b'|'f'|'n'|'r'|'t'|UCode);
UCode	:	'u' ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F');
Keyword	:	'true' | 'false' | 'null';
String	:	'"' (Control? Tz)* '"';
object	:       '{' {System.out.println(Indent + "{Object}"); Indent += "    ";} (pair (',' pair*)*)? '}' {Indent = Indent.substring(4);};
pair	:	e = String {System.out.println(Indent + "{Property}\t" + $e.text);} ':' value;
value	:	Number             {System.out.println(Indent + "{Number}  \t" + $Number.text);}
	|	object
	|	String             {System.out.println(Indent + "{String}  \t" + $String.text);}
	|	Keyword            {System.out.println(Indent + "{Keyword} \t" + $Keyword.text);}
	|	array;
array	:	'[' {System.out.println(Indent + "Array"); Indent += "    ";} (value (',' value)*)? ']' {Indent = Indent.substring(4);};
Task: JSON







Python: >>> import json
>>> data = json.loads('{ "foo": 1, "bar": [10, "apples"] }')
>>> sample = { "blue": [1,2], "ocean": "water" }
>>> json_string = json.dumps(sample)
>>> json_string
'{"blue": [1, 2], "ocean": "water"}'
>>> sample
{'blue': [1, 2], 'ocean': 'water'}
>>> data
{'foo': 1, 'bar': [10, 'apples']}
Task: JSON








VB: #include "inc/fbJSON.bas"

Sub printNodeChildren(Byval n As fbJSON Ptr, Byval level As Integer)
End Sub

Dim test As fbJSON Ptr = fbJSON_ImportFile("test1.json")

If test = NULL Then
	Print "Unable to load json file/string!"
	End 1
End If

Print fbJSON_ExportString(test, 1)

fbJSON_Delete(test)

Sleep
Task: JSON




Go: package main

import "encoding/json"
import "fmt"

func main() {
    var data interface{}
    err := json.Unmarshal([]byte(`{"foo":1, "bar":[10, "apples"]}`), &data)
    if err == nil {
        fmt.Println(data)
    } else {
        fmt.Println(err)
    }

    sample := map[string]interface{}{
        "blue":  []interface{}{1, 2},
        "ocean": "water",
    }
    json_string, err := json.Marshal(sample)
    if err == nil {
        fmt.Println(string(json_string))
    } else {
        fmt.Println(err)
    }
}
Task: JSON



C#: using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

class Program
{
    static void Main()
    {
        var people = new Dictionary<string, object> {{"1", "John"}, {"2", "Susan"}};
        var serializer = new JavaScriptSerializer();
        
        var json = serializer.Serialize(people);
        Console.WriteLine(json);

        var deserialized = serializer.Deserialize<Dictionary<string, object>>(json);
        Console.WriteLine(deserialized["2"]);

        var jsonObject = serializer.DeserializeObject(@"{ ""foo"": 1, ""bar"": [10, ""apples""] }");
        var data = jsonObject as Dictionary<string, object>;
        var array = data["bar"] as object[];
        Console.WriteLine(array[1]);
    }
}








Fortran: program json_fortran
   use json_module
   implicit none

   type phonebook_type
      character(len=:),allocatable :: name
      character(len=:),allocatable :: phone
   end type phonebook_type

   type(phonebook_type), dimension(3) :: PhoneBook
   integer :: i
   type(json_value),pointer :: json_phonebook,p,e
   type(json_file) :: json

   PhoneBook(1) % name = 'Adam'
   PhoneBook(2) % name = 'Eve'
   PhoneBook(3) % name = 'Julia'
   PhoneBook(1) % phone = '0000001'
   PhoneBook(2) % phone = '0000002'
   PhoneBook(3) % phone = '6666666'

   call json_initialize()

   
   call json_create_object(json_phonebook,'')

   
   call json_create_array(p,'PhoneBook')
   do i=1,3
      call json_create_object(e,'')
      call json_add(e,'name',PhoneBook(i)%name)
      call json_add(e,'phone',PhoneBook(i)%phone)
      call json_add(p,e) 
      nullify(e) 
   end do
   call json_add(json_phonebook,p) 
   nullify(p) 

   
   call json_print(json_phonebook,'phonebook.json')

   
   call json%load_from_string('{ "PhoneBook": [ { "name": "Adam", "phone": "0000001" },&
   { "name": "Eve", "phone": "0000002" }, { "name": "Julia", "phone": "6666666" } ]}')
   
   call json%print_file()

end program json_fortran
Task: JSON


C++: #include "Core/Core.h"

using namespace Upp;

CONSOLE_APP_MAIN
{
	JsonArray a;
	a << Json("name", "John")("phone", "1234567") << Json("name", "Susan")("phone", "654321");
	String txt = ~a;
	Cout() << txt << '\n';
	Value v = ParseJSON(txt);
	for(int i = 0; i < v.GetCount(); i++)
		Cout() << v[i]["name"] << ' ' << v[i]["phone"] << '\n';
}









Fortran: program json_fortran
   use json_module
   implicit none

   type phonebook_type
      character(len=:),allocatable :: name
      character(len=:),allocatable :: phone
   end type phonebook_type

   type(phonebook_type), dimension(3) :: PhoneBook
   integer :: i
   type(json_value),pointer :: json_phonebook,p,e
   type(json_file) :: json

   PhoneBook(1) % name = 'Adam'
   PhoneBook(2) % name = 'Eve'
   PhoneBook(3) % name = 'Julia'
   PhoneBook(1) % phone = '0000001'
   PhoneBook(2) % phone = '0000002'
   PhoneBook(3) % phone = '6666666'

   call json_initialize()

   
   call json_create_object(json_phonebook,'')

   
   call json_create_array(p,'PhoneBook')
   do i=1,3
      call json_create_object(e,'')
      call json_add(e,'name',PhoneBook(i)%name)
      call json_add(e,'phone',PhoneBook(i)%phone)
      call json_add(p,e) 
      nullify(e) 
   end do
   call json_add(json_phonebook,p) 
   nullify(p) 

   
   call json_print(json_phonebook,'phonebook.json')

   
   call json%load_from_string('{ "PhoneBook": [ { "name": "Adam", "phone": "0000001" },&
   { "name": "Eve", "phone": "0000002" }, { "name": "Julia", "phone": "6666666" } ]}')
   
   call json%print_file()

end program json_fortran
Task: JSON





Java: 



grammar JSON ;
@members {
String Indent = "";
}
Number	:	(('0')|('-'? ('1'..'9') ('0'..'9')*)) ('.' ('0'..'9')+)? (('e'|'E') ('+'|'-')? ('0'..'9')+)?;
WS	:	(' ' | '\t' | '\r' |'\n') {skip();};
Tz	:	' ' .. '!' | '#' .. '[' | ']' .. '~';
Control	:	'\\' ('"'|'\\'|'/'|'b'|'f'|'n'|'r'|'t'|UCode);
UCode	:	'u' ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F');
Keyword	:	'true' | 'false' | 'null';
String	:	'"' (Control? Tz)* '"';
object	:       '{' {System.out.println(Indent + "{Object}"); Indent += "    ";} (pair (',' pair*)*)? '}' {Indent = Indent.substring(4);};
pair	:	e = String {System.out.println(Indent + "{Property}\t" + $e.text);} ':' value;
value	:	Number             {System.out.println(Indent + "{Number}  \t" + $Number.text);}
	|	object
	|	String             {System.out.println(Indent + "{String}  \t" + $String.text);}
	|	Keyword            {System.out.println(Indent + "{Keyword} \t" + $Keyword.text);}
	|	array;
array	:	'[' {System.out.println(Indent + "Array"); Indent += "    ";} (value (',' value)*)? ']' {Indent = Indent.substring(4);};






Fortran: program json_fortran
   use json_module
   implicit none

   type phonebook_type
      character(len=:),allocatable :: name
      character(len=:),allocatable :: phone
   end type phonebook_type

   type(phonebook_type), dimension(3) :: PhoneBook
   integer :: i
   type(json_value),pointer :: json_phonebook,p,e
   type(json_file) :: json

   PhoneBook(1) % name = 'Adam'
   PhoneBook(2) % name = 'Eve'
   PhoneBook(3) % name = 'Julia'
   PhoneBook(1) % phone = '0000001'
   PhoneBook(2) % phone = '0000002'
   PhoneBook(3) % phone = '6666666'

   call json_initialize()

   
   call json_create_object(json_phonebook,'')

   
   call json_create_array(p,'PhoneBook')
   do i=1,3
      call json_create_object(e,'')
      call json_add(e,'name',PhoneBook(i)%name)
      call json_add(e,'phone',PhoneBook(i)%phone)
      call json_add(p,e) 
      nullify(e) 
   end do
   call json_add(json_phonebook,p) 
   nullify(p) 

   
   call json_print(json_phonebook,'phonebook.json')

   
   call json%load_from_string('{ "PhoneBook": [ { "name": "Adam", "phone": "0000001" },&
   { "name": "Eve", "phone": "0000002" }, { "name": "Julia", "phone": "6666666" } ]}')
   
   call json%print_file()

end program json_fortran
Task: JSON







Python: >>> import json
>>> data = json.loads('{ "foo": 1, "bar": [10, "apples"] }')
>>> sample = { "blue": [1,2], "ocean": "water" }
>>> json_string = json.dumps(sample)
>>> json_string
'{"blue": [1, 2], "ocean": "water"}'
>>> sample
{'blue': [1, 2], 'ocean': 'water'}
>>> data
{'foo': 1, 'bar': [10, 'apples']}




Fortran: program json_fortran
   use json_module
   implicit none

   type phonebook_type
      character(len=:),allocatable :: name
      character(len=:),allocatable :: phone
   end type phonebook_type

   type(phonebook_type), dimension(3) :: PhoneBook
   integer :: i
   type(json_value),pointer :: json_phonebook,p,e
   type(json_file) :: json

   PhoneBook(1) % name = 'Adam'
   PhoneBook(2) % name = 'Eve'
   PhoneBook(3) % name = 'Julia'
   PhoneBook(1) % phone = '0000001'
   PhoneBook(2) % phone = '0000002'
   PhoneBook(3) % phone = '6666666'

   call json_initialize()

   
   call json_create_object(json_phonebook,'')

   
   call json_create_array(p,'PhoneBook')
   do i=1,3
      call json_create_object(e,'')
      call json_add(e,'name',PhoneBook(i)%name)
      call json_add(e,'phone',PhoneBook(i)%phone)
      call json_add(p,e) 
      nullify(e) 
   end do
   call json_add(json_phonebook,p) 
   nullify(p) 

   
   call json_print(json_phonebook,'phonebook.json')

   
   call json%load_from_string('{ "PhoneBook": [ { "name": "Adam", "phone": "0000001" },&
   { "name": "Eve", "phone": "0000002" }, { "name": "Julia", "phone": "6666666" } ]}')
   
   call json%print_file()

end program json_fortran
Task: JSON








VB: #include "inc/fbJSON.bas"

Sub printNodeChildren(Byval n As fbJSON Ptr, Byval level As Integer)
End Sub

Dim test As fbJSON Ptr = fbJSON_ImportFile("test1.json")

If test = NULL Then
	Print "Unable to load json file/string!"
	End 1
End If

Print fbJSON_ExportString(test, 1)

fbJSON_Delete(test)

Sleep



Fortran: program json_fortran
   use json_module
   implicit none

   type phonebook_type
      character(len=:),allocatable :: name
      character(len=:),allocatable :: phone
   end type phonebook_type

   type(phonebook_type), dimension(3) :: PhoneBook
   integer :: i
   type(json_value),pointer :: json_phonebook,p,e
   type(json_file) :: json

   PhoneBook(1) % name = 'Adam'
   PhoneBook(2) % name = 'Eve'
   PhoneBook(3) % name = 'Julia'
   PhoneBook(1) % phone = '0000001'
   PhoneBook(2) % phone = '0000002'
   PhoneBook(3) % phone = '6666666'

   call json_initialize()

   
   call json_create_object(json_phonebook,'')

   
   call json_create_array(p,'PhoneBook')
   do i=1,3
      call json_create_object(e,'')
      call json_add(e,'name',PhoneBook(i)%name)
      call json_add(e,'phone',PhoneBook(i)%phone)
      call json_add(p,e) 
      nullify(e) 
   end do
   call json_add(json_phonebook,p) 
   nullify(p) 

   
   call json_print(json_phonebook,'phonebook.json')

   
   call json%load_from_string('{ "PhoneBook": [ { "name": "Adam", "phone": "0000001" },&
   { "name": "Eve", "phone": "0000002" }, { "name": "Julia", "phone": "6666666" } ]}')
   
   call json%print_file()

end program json_fortran
Task: JSON






PHP: <?php
$data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects
$data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays

$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?>





Fortran: program json_fortran
   use json_module
   implicit none

   type phonebook_type
      character(len=:),allocatable :: name
      character(len=:),allocatable :: phone
   end type phonebook_type

   type(phonebook_type), dimension(3) :: PhoneBook
   integer :: i
   type(json_value),pointer :: json_phonebook,p,e
   type(json_file) :: json

   PhoneBook(1) % name = 'Adam'
   PhoneBook(2) % name = 'Eve'
   PhoneBook(3) % name = 'Julia'
   PhoneBook(1) % phone = '0000001'
   PhoneBook(2) % phone = '0000002'
   PhoneBook(3) % phone = '6666666'

   call json_initialize()

   
   call json_create_object(json_phonebook,'')

   
   call json_create_array(p,'PhoneBook')
   do i=1,3
      call json_create_object(e,'')
      call json_add(e,'name',PhoneBook(i)%name)
      call json_add(e,'phone',PhoneBook(i)%phone)
      call json_add(p,e) 
      nullify(e) 
   end do
   call json_add(json_phonebook,p) 
   nullify(p) 

   
   call json_print(json_phonebook,'phonebook.json')

   
   call json%load_from_string('{ "PhoneBook": [ { "name": "Adam", "phone": "0000001" },&
   { "name": "Eve", "phone": "0000002" }, { "name": "Julia", "phone": "6666666" } ]}')
   
   call json%print_file()

end program json_fortran
Task: JSON






PHP: <?php
$data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects
$data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays

$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?>
Task: JSON






PHP: <?php
$data = json_decode('{ "foo": 1, "bar": [10, "apples"] }'); // dictionaries will be returned as objects
$data2 = json_decode('{ "foo": 1, "bar": [10, "apples"] }', true); // dictionaries will be returned as arrays

$sample = array( "blue" => array(1,2), "ocean" => "water" );
$json_string = json_encode($sample);
?>






Ada: with Ada.Text_IO;
with GNATCOLL.JSON;
 
procedure JSON_Test is
   use Ada.Text_IO;
   use GNATCOLL.JSON;
 
   JSON_String : constant String := "{""name"":""Pingu"",""born"":1986}";
   
   Penguin : JSON_Value := Create_Object;
   Parents : JSON_Array;
begin
   Penguin.Set_Field (Field_Name => "name", 
                      Field      => "Linux");
   
   Penguin.Set_Field (Field_Name => "born",
                      Field      => 1992);
   
   Append (Parents, Create ("Linus Torvalds"));
   Append (Parents, Create ("Alan Cox"));
   Append (Parents, Create ("Greg Kroah-Hartman"));
 
   Penguin.Set_Field (Field_Name => "parents",
                      Field      => Parents);
   
   Put_Line (Penguin.Write);

   Penguin := Read (JSON_String, "json.errors");
   
   Penguin.Set_Field (Field_Name => "born",
                      Field      => 1986);
   
   Parents := Empty_Array;
   Append (Parents, Create ("Otmar Gutmann"));
   Append (Parents, Create ("Silvio Mazzola"));  
   
   Penguin.Set_Field (Field_Name => "parents",
                      Field      => Parents);
   
   Put_Line (Penguin.Write);
end JSON_Test;
Task: Check that file exists



C#: using System.IO;

Console.WriteLine(File.Exists("input.txt"));
Console.WriteLine(File.Exists("/input.txt"));
Console.WriteLine(Directory.Exists("docs"));
Console.WriteLine(Directory.Exists("/docs"));









Ada: with Ada.Text_IO; use Ada.Text_IO;

procedure File_Exists is
   function Does_File_Exist (Name : String) return Boolean is
      The_File : Ada.Text_IO.File_Type;
   begin
      Open (The_File, In_File, Name);
      Close (The_File);
      return True;
   exception
      when Name_Error =>
         return False;
   end Does_File_Exist;
begin
   Put_Line (Boolean'Image (Does_File_Exist ("input.txt" )));
   Put_Line (Boolean'Image (Does_File_Exist ("\input.txt")));
end File_Exists;
Task: Check that file exists

C: #include <sys/types.h> 
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>


int check_reg(const char *path) {
	struct stat sb;
	return stat(path, &sb) == 0 && S_ISREG(sb.st_mode);
}


int check_dir(const char *path) {
	struct stat sb;
	return stat(path, &sb) == 0 && S_ISDIR(sb.st_mode);
}

int main() {
	printf("input.txt is a regular file? %s\n",
	    check_reg("input.txt") ? "yes" : "no");
	printf("docs is a directory? %s\n",
	    check_dir("docs") ? "yes" : "no");
	printf("/input.txt is a regular file? %s\n",
	    check_reg("/input.txt") ? "yes" : "no");
	printf("/docs is a directory? %s\n",
	    check_dir("/docs") ? "yes" : "no");
	return 0;
}











Ada: with Ada.Text_IO; use Ada.Text_IO;

procedure File_Exists is
   function Does_File_Exist (Name : String) return Boolean is
      The_File : Ada.Text_IO.File_Type;
   begin
      Open (The_File, In_File, Name);
      Close (The_File);
      return True;
   exception
      when Name_Error =>
         return False;
   end Does_File_Exist;
begin
   Put_Line (Boolean'Image (Does_File_Exist ("input.txt" )));
   Put_Line (Boolean'Image (Does_File_Exist ("\input.txt")));
end File_Exists;
Task: Check that file exists


C++: #include "boost/filesystem.hpp"
#include <string>
#include <iostream>

void testfile(std::string name)
{
  boost::filesystem::path file(name);
  if (exists(file))
  {
    if (is_directory(file))
      std::cout << name << " is a directory.\n";
    else
      std::cout << name << " is a non-directory file.\n";
  }
  else
    std::cout << name << " does not exist.\n";
}

int main()
{
  testfile("input.txt");
  testfile("docs");
  testfile("/input.txt");
  testfile("/docs");
}










Ada: with Ada.Text_IO; use Ada.Text_IO;

procedure File_Exists is
   function Does_File_Exist (Name : String) return Boolean is
      The_File : Ada.Text_IO.File_Type;
   begin
      Open (The_File, In_File, Name);
      Close (The_File);
      return True;
   exception
      when Name_Error =>
         return False;
   end Does_File_Exist;
begin
   Put_Line (Boolean'Image (Does_File_Exist ("input.txt" )));
   Put_Line (Boolean'Image (Does_File_Exist ("\input.txt")));
end File_Exists;
Task: Check that file exists




Go: package main

import (
    "fmt"
    "os"
)

func printStat(p string) {
    switch i, err := os.Stat(p); {
    case err != nil:
        fmt.Println(err)
    case i.IsDir():
        fmt.Println(p, "is a directory")
    default:
        fmt.Println(p, "is a file")
    }
}

func main() {
    printStat("input.txt")
    printStat("/input.txt")
    printStat("docs")
    printStat("/docs")
}








Ada: with Ada.Text_IO; use Ada.Text_IO;

procedure File_Exists is
   function Does_File_Exist (Name : String) return Boolean is
      The_File : Ada.Text_IO.File_Type;
   begin
      Open (The_File, In_File, Name);
      Close (The_File);
      return True;
   exception
      when Name_Error =>
         return False;
   end Does_File_Exist;
begin
   Put_Line (Boolean'Image (Does_File_Exist ("input.txt" )));
   Put_Line (Boolean'Image (Does_File_Exist ("\input.txt")));
end File_Exists;
Task: Check that file exists





Java: import java.io.File;
public class FileExistsTest {
   public static boolean isFileExists(String filename) {
       boolean exists = new File(filename).exists();
       return exists;
   }
   public static void test(String type, String filename) {
       System.out.println("The following " + type + " called " + filename + 
           (isFileExists(filename) ? " exists." : " not exists.")
       );
   }
   public static void main(String args[]) {
        test("file", "input.txt");
        test("file", File.separator + "input.txt");
        test("directory", "docs");
        test("directory", File.separator + "docs" + File.separator);
   }
}







Ada: with Ada.Text_IO; use Ada.Text_IO;

procedure File_Exists is
   function Does_File_Exist (Name : String) return Boolean is
      The_File : Ada.Text_IO.File_Type;
   begin
      Open (The_File, In_File, Name);
      Close (The_File);
      return True;
   exception
      when Name_Error =>
         return False;
   end Does_File_Exist;
begin
   Put_Line (Boolean'Image (Does_File_Exist ("input.txt" )));
   Put_Line (Boolean'Image (Does_File_Exist ("\input.txt")));
end File_Exists;
Task: Check that file exists







Python: import os

os.path.isfile("input.txt")
os.path.isfile("/input.txt")
os.path.isdir("docs")
os.path.isdir("/docs")





Ada: with Ada.Text_IO; use Ada.Text_IO;

procedure File_Exists is
   function Does_File_Exist (Name : String) return Boolean is
      The_File : Ada.Text_IO.File_Type;
   begin
      Open (The_File, In_File, Name);
      Close (The_File);
      return True;
   exception
      when Name_Error =>
         return False;
   end Does_File_Exist;
begin
   Put_Line (Boolean'Image (Does_File_Exist ("input.txt" )));
   Put_Line (Boolean'Image (Does_File_Exist ("\input.txt")));
end File_Exists;
Task: Check that file exists








VB: Option Explicit

Sub Main_File_Exists()
Dim myFile As String, myDirectory As String
    
    myFile = "Abdu
    myDirectory = "C:\"
    Debug.Print File_Exists(myFile, myDirectory)
End Sub

Function File_Exists(F As String, D As String) As Boolean
    If F = "" Then
        File_Exists = False
    Else
        D = IIf(Right(D, 1) = "\", D, D & "\")
        File_Exists = (Dir(D & F) <> "")
    End If
End Function




Ada: with Ada.Text_IO; use Ada.Text_IO;

procedure File_Exists is
   function Does_File_Exist (Name : String) return Boolean is
      The_File : Ada.Text_IO.File_Type;
   begin
      Open (The_File, In_File, Name);
      Close (The_File);
      return True;
   exception
      when Name_Error =>
         return False;
   end Does_File_Exist;
begin
   Put_Line (Boolean'Image (Does_File_Exist ("input.txt" )));
   Put_Line (Boolean'Image (Does_File_Exist ("\input.txt")));
end File_Exists;
Task: Check that file exists

C: #include <sys/types.h> 
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>


int check_reg(const char *path) {
	struct stat sb;
	return stat(path, &sb) == 0 && S_ISREG(sb.st_mode);
}


int check_dir(const char *path) {
	struct stat sb;
	return stat(path, &sb) == 0 && S_ISDIR(sb.st_mode);
}

int main() {
	printf("input.txt is a regular file? %s\n",
	    check_reg("input.txt") ? "yes" : "no");
	printf("docs is a directory? %s\n",
	    check_dir("docs") ? "yes" : "no");
	printf("/input.txt is a regular file? %s\n",
	    check_reg("/input.txt") ? "yes" : "no");
	printf("/docs is a directory? %s\n",
	    check_dir("/docs") ? "yes" : "no");
	return 0;
}
Task: Check that file exists



C#: using System.IO;

Console.WriteLine(File.Exists("input.txt"));
Console.WriteLine(File.Exists("/input.txt"));
Console.WriteLine(Directory.Exists("docs"));
Console.WriteLine(Directory.Exists("/docs"));
Task: Check that file exists


C++: #include "boost/filesystem.hpp"
#include <string>
#include <iostream>

void testfile(std::string name)
{
  boost::filesystem::path file(name);
  if (exists(file))
  {
    if (is_directory(file))
      std::cout << name << " is a directory.\n";
    else
      std::cout << name << " is a non-directory file.\n";
  }
  else
    std::cout << name << " does not exist.\n";
}

int main()
{
  testfile("input.txt");
  testfile("docs");
  testfile("/input.txt");
  testfile("/docs");
}
Task: Check that file exists





Java: import java.io.File;
public class FileExistsTest {
   public static boolean isFileExists(String filename) {
       boolean exists = new File(filename).exists();
       return exists;
   }
   public static void test(String type, String filename) {
       System.out.println("The following " + type + " called " + filename + 
           (isFileExists(filename) ? " exists." : " not exists.")
       );
   }
   public static void main(String args[]) {
        test("file", "input.txt");
        test("file", File.separator + "input.txt");
        test("directory", "docs");
        test("directory", File.separator + "docs" + File.separator);
   }
}
Task: Check that file exists







Python: import os

os.path.isfile("input.txt")
os.path.isfile("/input.txt")
os.path.isdir("docs")
os.path.isdir("/docs")
Task: Check that file exists








VB: Option Explicit

Sub Main_File_Exists()
Dim myFile As String, myDirectory As String
    
    myFile = "Abdu
    myDirectory = "C:\"
    Debug.Print File_Exists(myFile, myDirectory)
End Sub

Function File_Exists(F As String, D As String) As Boolean
    If F = "" Then
        File_Exists = False
    Else
        D = IIf(Right(D, 1) = "\", D, D & "\")
        File_Exists = (Dir(D & F) <> "")
    End If
End Function