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.


Pages: 1 2

4 Responses to “Longest Line”

  1. Rutger said

    Option 1:
    wc -L filename

    Option 2:

    def longest_line(filename):
    	line, length = "", -1
    	with open(filename, 'r') as file_handler:
    	    for l in file_handler:
    	    	if len(l) > length:
    	    		line, length = l, len(l)
    	return line, length 
  2. Paul said
    def longest_line(fname, encoding="UTF-8"):
        with open(fname, encoding=encoding) as f:
            return max((line for line in f), key=len)
    def longest_silly(fname, encoding="UTF-8"):
        line = ""
        with open(fname, encoding=encoding) as f:
            txt = f.read()
            pos, length = 0, -1
            ind = txt.find("\n")
            while ind > -1:
                if ind - pos > length:
                    length, line = ind - pos, txt[pos:ind]
                pos = ind+1
                ind = txt.find("\n", pos)
        return line
  3. john said

    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) {
            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) {

      printf("length: %zd\n", strlen(longest));
      printf("longest: %s", longest);


  4. Returning all the longest lines in perl

      my @L = (q());
      while(<>) {
        next if length $L[0] > length $_;
        @L = () if length $L[0] < length $_;
        push @L, $_;
      return @L;

    or you can do it with bash

    while read l
      if [ $z -lt ${#l}
     echo $x

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: