一次写入文件并读取文件的全部内容

Contents

输出结果

Hello World!
Additional line
 

程式码


JavaScript

const fs = require('fs');
let output_file = "/tmp/output_js.txt";
fs.writeFile(output_file, "Hello World!\nAdditional line\n", (err, resp) => {
    if (err) throw err;
    fs.readFile(output_file, (err, data) => {
	if (err) throw err;
        process.stdout.write(data.toString());
    });
});

PHP

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

print file_get_contents($output_file);

Perl

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

if(my $fh = new FileHandle($output_file) ){
  local $/ = undef;
  print <$fh>;
  $fh->close();
}

Python

import sys
output_file = "/tmp/output_python.txt"
try:
  with open(output_file, "w") as wfh:
    wfh.write("Hello World!\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)

with open(output_file, "r") as rfh:
  print(rfh.read(), end="")

Ruby

output_file = "/tmp/output_ruby.txt"
begin
  File.open(output_file, "w") do |wfh|
    wfh.puts("Hello World!\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

File.open(output_file, "r") do |rfh|
  print(rfh.read())
end

Shell

#!/bin/bash
output_file="/tmp/output_shell.txt";
echo -e -n 'Hello World!\nAdditional line\n' > $output_file || exit 1;
cat $output_file;