Reputation: 32083
I'm making a console-based application in Objective-C which relies on being able to clear the console periodically. How can this be done? All I've seen on SO and Google were ways to have the developer clear the console with X-Code, but that will not do.
One solution I found on Yahoo! Answers told me to do the following, but it does not run due to being unable to find a file:
NSTask *task;
task = [[NSTask alloc]init];
[task setLaunchPath: @"/bin/bash"];
NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"clear", nil];
[task setArguments: arguments];
[task launch];
[task waitUntilExit];
Upvotes: 8
Views: 4341
Reputation: 22930
You can use apple script
tell application "Console"
activate
tell application "System Events"
keystroke "k" using command down
end tell
end tell
Use NSAppleScript class for executing applescript from obj-C program.
NSAppleScript *lClearDisplay = [[NSAppleScript alloc] initWithSource:@"tell application \"Console\"\n \
activate\n \
tell application \"System Events\"\n \
keystroke \"k\" using command down\n \
end tell\n \
end tell "];
NSDictionary *errorInfo;
[lClearDisplay executeAndReturnError:&errorInfo];
NOTE:
If Apple changes or removes ⌘k as the key command for clear display, that will break script.
Upvotes: 1
Reputation: 22810
Try using :
system( "clear" );
Important headers :
#include <stdlib.h>
Hint : Objective-C is still C, right?
UPDATE :
In case of a "TERM environment variable not set." error :
1) Run the program, directly from your terminal (or just ignore the error while testing it in Xcode; it's supposed to run in a normal terminal anyway, huh?)
2) Set the TERM variable in your Scheme's settings. To what? Just run this in your terminal to see what "TERM" should be :
DrKameleons-MacBook-Pro:Documents drkameleon$ echo $TERM
xterm-256color
Upvotes: 6
Reputation: 90531
The way to do this without spawning a subprocess is to use ncurses.
#include <curses.h>
#include <term.h>
#include <unistd.h>
int main(void)
{
setupterm(NULL, STDOUT_FILENO, NULL);
tputs(clear_screen, lines ? lines : 1, putchar);
}
Compile with -lncurses
.
The setupterm()
call only needs to be done once. After that, use the tputs()
call to clear the screen.
Upvotes: 4
Reputation: 33392
Why /bin/bash
?
Just do:
NSTask *task = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/clear" arguments:[NSArray array]];
Alternatively, using the C way:
#include <stdlib.h>
...
system("/usr/bin/clear");
...
Upvotes: 3