Line Filters in Objective-C
A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep
and sed
are common line filters.
Here’s an example line filter in Objective-C that writes a capitalized version of all input text. You can use this pattern to write your own Objective-C line filters.
In this Objective-C version:
- We use
NSFileHandle
to read from standard input. - We read all the input data at once using
readDataToEndOfFile
. - We convert the input data to a string and split it into lines.
- We iterate over each line, convert it to uppercase, and print it.
To check for errors, we could add error handling around the file operations, but for simplicity, this example assumes the input will be valid.
To try out our line filter, first make a file with a few lowercase lines.
Then use the line filter to get uppercase lines. Assuming you’ve compiled the Objective-C program to an executable named line-filter
:
Note that NSLog
adds a timestamp to each line by default. To get clean output without timestamps, you could replace NSLog(@"%@", uppercaseLine);
with printf("%s\n", [uppercaseLine UTF8String]);
.
This Objective-C version provides similar functionality to the original example, reading input line by line, processing it, and writing the result to stdout.