Longest Line
April 18, 2017
Today’s exercise is simple:
Write a program that prints the longest line in a file. If there is a tie for the longest line, you may print any of the longest lines, or all of them, at your option.
There are lots of ways to solve this problem, and I expect that my fun-loving readers will come up with some outlandish solutions, so to make this a sensible exercise we add two rules: First, if you comment you must provide at least two solutions. Second, at least one of your solutions must be “reasonable” in the sense that you would actually use it in a production environment.
Your task is to write a program to find the longest line in a file. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Option 1:
wc -L filename
Option 2:
Here are two solutions: Perl 5 and C11. They both expect filenames to be passed as command line arguments (- for stdin).
The Perl solution:
#!/usr/bin/env perl
my $longest = "\n";
while (<>) {
$longest = $_ if (length($longest) < length);
}
print "length: " . length($longest) . "\n";
print "longest: " . $longest;
The C11 solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
const size_t max_line_length = 1024;
char *filename;
FILE *fp;
char line[max_line_length];
char longest[max_line_length];
int err;
longest[0] = '\0';
for (int i = 1; i < argc; ++i) {
filename = argv[i];
if (strcmp(filename, "-") == 0) {
fp = stdin;
} else {
fp = fopen(filename, "r");
if (fp == NULL) {
perror(filename);
continue; // ignore bad files
}
}
while (fgets(line, max_line_length, fp) != NULL) {
if (strlen(line) > strlen(longest)) {
(void)memcpy(longest, line, max_line_length);
}
}
if (!feof(fp)) {
err = fprintf(stderr, "There was an error while reading %s.\n", filename);
if (err < 0) {
exit(1);
}
}
}
printf("length: %zd\n", strlen(longest));
printf("longest: %s", longest);
exit(0);
}
Returning all the longest lines in perl
or you can do it with bash