Write to file and read content of file line by line

Contents

Output

Hello World!

Additional line


Code examples


JavaScript

const fs = require('fs');
const readline = require('readline');
let output_file = "/tmp/output_js.txt";
let line_cnt = 0;
fs.writeFile(output_file, "Hello World!\n\nAdditional line\n", (err, resp) => {
  if (err) throw err;
  const fileStream = fs.createReadStream(output_file);
  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });
  rl.on('line', (line) => {
    console.log(`${line}`);
    line_cnt++;
  });
  rl.on('close', ()=>{console.log(line_cnt);});
});

PHP

<?php
$output_file = "/tmp/output_php.txt";
try {
  $fh = fopen($output_file, "w");
  fwrite($fh, "Hello World!\n\nAdditional line\n");
  fclose($fh);
}
catch (Exception $e) {
  echo $e->getMessage();
  exit;
}

$cnt = 0;
if($fh = fopen($output_file, "r") ){
  while($line = fgets($fh)) {
    print $line;
    $cnt++;
  }
  fclose($fh);
  print $cnt."\n";
}

Perl

use strict;
use FileHandle;
my $output_file = "/tmp/output_perl.txt";
if(my $fh = new FileHandle('> '.$output_file) ){
  print $fh "Hello World!\n\nAdditional line\n";
  $fh->close();
}
else{
  die("Failed to write to ".$output_file);
}

if(my $fh = new FileHandle($output_file) ){
  my $cnt = 0;
  while(<$fh>){
    print $_;
    $cnt++;
  }
  $fh->close();
  print $cnt."\n";
}

Python

import sys
output_file = "/tmp/output_python.txt"
try:
  with open(output_file, "w") as wfh:
    wfh.write("Hello World!\n\nAdditional line\n")
except IOError:
  print("Failed to write to " + output_file)
  sys.exit(1)
except:
  print("Unexpected error:", sys.exc_info()[0])
  sys.exit(1)

line_cnt = 0
with open(output_file, "r") as rfh:
  for line in rfh:
    print(line.rstrip("\n"))
    line_cnt += 1
print(line_cnt)

Ruby

output_file = "/tmp/output_ruby.txt"
begin
  File.open(output_file, "w") do |wfh|
    wfh.puts("Hello World!\n\nAdditional line\n")
  end
rescue SystemCallError => e
  puts "class=#{e.class},message=#{e.message}"
rescue IOError => e
  puts "class=#{e.class},message=#{e.message}"
end

line_cnt = 0
File.open(output_file, "r") do |rfh|
  while (line = rfh.gets)
    puts line
    line_cnt += 1
  end
end

puts line_cnt

Shell

#!/bin/bash
output_file="/tmp/output_shell.txt";
echo -e -n 'Hello World!\n\nAdditional line\n' > $output_file || exit 1;
line_cnt=0;
while IFS= read -r line
do
  echo "$line"
  line_cnt=$((line_cnt + 1))
done <"$output_file"
echo $line_cnt;