Check output device is a terminal: Difference between revisions

Added Wren
m (→‎{{header|Quackery}}: changed in to out. D'oh.)
(Added Wren)
Line 664:
 
End Module</lang>
 
=={{header|Wren}}==
{{trans|C}}
As there is currently no way to obtain this information via Wren CLI, we instead embed a Wren script in a C application and ask the host program to get it for us.
<lang ecmascript>/* check_output_device_is_terminal.wren */
 
class C {
foreign static isOutputDeviceTerminal
}
 
System.print("Output device is a terminal = %(C.isOutputDeviceTerminal)")</lang>
<br>
We now embed this Wren script in the following C program, compile and run it.
<lang c>#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include "wren.h"
 
void C_isOutputDeviceTerminal(WrenVM* vm) {
bool isTerminal = (bool)isatty(fileno(stdout));
wrenSetSlotBool(vm, 0, isTerminal);
}
 
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "isOutputDeviceTerminal") == 0) {
return C_isOutputDeviceTerminal;
}
}
}
return NULL;
}
 
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
 
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
 
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
 
int main() {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "check_output_device_is_terminal.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}</lang>
 
{{out}}
<pre>
$ ./check_output_device_is_terminal
Output device is a terminal = true
 
$ ./check_output_device_is_terminal > tmp
$ cat tmp
Output device is a terminal = false
 
$ ./check_output_device_is_terminal | cat
Output device is a terminal = false
</pre>
 
=={{header|zkl}}==
9,476

edits