File input/output: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎[[Java]]: fixed typoe)
(→‎[[AppleScript]]: replaced with a more appropriate example)
Line 26: Line 26:
==[[AppleScript]]==
==[[AppleScript]]==
[[Category:AppleScript]]
[[Category:AppleScript]]
on copyFile from src into dst
tell application "Finder"
set filedata to read file src
duplicate (choose file "Choose file to copy") to (choose folder "Choose location to make copy")
set outfile to open for access dst with write permission
end tell
write filedata to outfile
close access outfile
end copyFile
copyFile from ":input.txt" into ":output.txt"


==[[BASIC]]==
==[[BASIC]]==

Revision as of 06:01, 28 January 2007

Task
File input/output
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the job is to create a file called "output.txt", and place in it the contents of the file "input.txt".

Ada

Compiler: GCC 4.1.2

with Ada.Text_IO; use Ada.Text_IO;
procedure File_IO is
 Input, Output : File_Type;
 Line : String (1 .. 10_000);
 Last : Natural;
begin
 Create (Output, Out_File, "output.txt");
 Open (Input, In_File, "input.txt");
 while not End_Of_File (Input) loop
  Get_Line (Input, Line, Last);
  Put_Line (Output, Line (1 .. Last));
 end loop;
 Close (Input);
 Close (Output);
end File_IO;

AppleScript

on copyFile from src into dst
	set filedata to read file src
	set outfile to open for access dst with write permission
	write filedata to outfile
	close access outfile
end copyFile

copyFile from ":input.txt" into ":output.txt"

BASIC

Compiler: QuickBasic 4.5

OPEN "INPUT.TXT" FOR INPUT AS #1
OPEN "OUTPUT.TXT" FOR OUTPUT AS #2
DO UNTIL EOF(1)
  LINE INPUT #1, Data$
  PRINT #2, Data$
LOOP
CLOSE #1
CLOSE #2
SYSTEM

C

Compiler: GCC 4.1.2

#include <stdio.h>

int main(int argc, char **argv) {
  FILE *in, *out;
  int c;

  in = fopen("input.txt", "r");
  if (!in) {
    fprintf(stderr, "Error opening input.txt for reading.\n");
    return 1;
  }

  out = fopen("output.txt", "w");
  if (!out) {
    fprintf(stderr, "Error opening output.txt for writing.\n");
    fclose(in);
    return 1;
  }

  while ((c = fgetc(in)) != EOF) {
    fputc(c, out);
  }

  fclose(out);
  fclose(in);
  return 0;
}

A couple of remarks on the preceding example:

It uses fgetc to read one character at a time. Each character is visited, even though there's nothing to do with it. Copying bigger blocks of data is much more efficient.

It uses buffered IO to perform the move, which is overkill. This is not actually a weakness, but it invokes some overhead that you don't need.

It doesn't close the files afer it's done, relying on them being closed and their output flushed when the program exits. Not a problem in this particular case, but a bad habit to get into.

An example that addresses these:

 #include <stdio.h>
 #include <unistd.h>
 #include <fcntl.h>
 
 int main(int argc, char **argv)
 { int   fi, fo;
   int   len;
   char  buf[1024];  /* a better choice is the FS block size, if you know it */
 
   if ((fi = open("input.txt", O_RDONLY)) < 0) {
     perror("Can't read input.txt");
     return 1;
   }
 
   if ((fo = open("output.txt", O_WRONLY|O_CREAT|O_TRUNC)) < 0) {
     perror("Can't write to output.txt");
     return 1;
   }
 
   while ((len = read(fi, buf, 1024)) > 0) {
     if (write(fo, buf, len) < 0) {
       perror("write failed");
       return 1;
     }
   }
 
   if (len < 0) {
     perror("read failed");
     return 1;
   }
 
   close(fi); close(fo);
   return 0;
 }

C#

Platform: .NET Language Version: 1.0+

   using System;
   using System.IO;
 
   namespace FileIO
   {
       class Program
       {
           static void Main(string[] args)
           {
               if (File.Exists("input.txt"))
               {
                   TextReader tr = File.OpenText("input.txt");
                   TextWriter tw = new StreamWriter(File.OpenWrite("output.txt"));

                   while (tr.Peek() != -1)
                   {
                       string line = tr.ReadLine();

                       tw.WriteLine(line);
                   }

                   tw.Close();
                   tr.Close();
               }
               else
               {
                   Console.WriteLine("Input File Missing.");
               }
           }
       }
   }

C++

Compiler: GCC 3.4.2

#include <iostream>
#include <fstream>
#include <string>

int main() {
    string line;
    ifstream input ( "input.txt" );
    ofstream output ("output.txt");
    
    if (output.is_open()) {
        if (input.is_open()){
            while (! input.eof() ) {
                getline (input,line);
                output << line << endl;
            }
            input.close();
        }
        else {
            cout << "input.txt cannot be opened!\n";
        }
        output.close();
    }
    else {
        cout << "output.txt cannot be written to!\n";
    }
    return 0;
}

Simpler version:

 #include <iostream>
 #include <istream>
 #include <ostream>
 #include <fstream>
 #include <cstdlib>
 
 int main()
 {
   std::ifstream input("input.txt");
   if (!input)
   {
     std::cerr << "could not open input.txt for reading.\n";
     return EXIT_FAILURE;
   }
   
   std::ofstream output("output.txt");
   if (!output)
   {
     std::cerr << "could not open output.txt for writing.\n";
     return EXIT_FAILURE;
   }
   
   output << input.rdbuf();
   if (!output)
   {
     std::cerr << "error copying the data.\n";
     return EXIT_FAILURE;
   }
   
   return EXIT_SUCCESS;
 }

Using istream- and ostream- iterators:

 # include <algorithm>
 # include <fstream>
 
 int main() {
   std::ifstream ifile("input.txt");
   std::ofstream ofile("output.txt");
   std::copy(std::istreambuf_iterator<char>(ifile),
             std::istreambuf_iterator<char>(),
             std::ostreambuf_iterator<char>(ofile));
 }

ColdFusion

<cfif fileExists(expandPath("input.txt"))>
  <cffile action="read" file="#expandPath('input.txt')#" variable="inputContents">
  <cffile action="write" file="#expandPath('output.txt')#" output="#inputContents#">
</cfif>

Haskell

Interpreter: GHCi

Note: this doesn't keep the file in memory. Buffering is provided by lazy evaluation.

copyFile from to = do
    filedata <- readFile from
    writeFile to filedata

main = copyFile "input.txt" "output.txt"

Java

Compiler: GCJ 4.1.2

Simple version; Files may be closed automatically by OS, on some systems. This example is broken: it needs a finally.

import java.io.*;

public class FileIODemo {
  public static void main(String[] args) {
    try {
      FileInputStream in = new FileInputStream("input.txt");
      FileOutputStream out = new FileOutputStream("ouput.txt");
      int c;
      while ((c = in.read()) != -1) {
        out.write(c);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

This version closes both files after without OS intervention

import java.io.*;

public class FileIODemo2 {
  public static void main(String args[]) {
    try {
      // Probably should wrap with a BufferedInputStream
      final InputStream in = new FileInputStream("input.txt");
      try {
        // Probably should wrap with a BufferedOutputStream
        final OutputStream out = new FileOutputStream("output.txt");
        try {
          int c;
          while ((c = in.read()) != -1) {
            out.write(c);
          }
        }
        finally {
          out.close();
        }
      }
      finally {
        in.close();
      }
    }
    catch (Exception e) {
      System.err.println("Exception while trying to copy: "+e);
      e.printStackTrace(); // stack trace of place where it happened
    }
  }
}


Language Version 1.4

Package nio

import java.io.*;
import java.nio.channels.*;

public class FileIODemo3 {
  public static void main(String args[]) {
    try {
      final FileChannel in = new FileInputStream("input.txt").getChannel();
      try {
        final FileChannel out = new FileOutputStream("output.txt").getChannel();
        try {
          out.transferFrom(in, 0, in.size());
        }
        finally {
          out.close();
        }
      }
      finally {
        in.close();
      }
    }
    catch (Exception e) {
      System.err.println("Exception while trying to copy: "+e);
      e.printStackTrace(); // stack trace of place where it happened
    }
  }
}

This version is more in line with the other languages' implementations: it assumes simple text files, and doesn't worry too much about errors (just throws them out to the caller, the console in this case). Its shorter and simpler and shows that simple programs can be simple to write, in Java as well.

 import java.io.*;
 public class Test {
   public static void main (String[] args) throws IOException {
     BufferedReader br = new BufferedReader(new FileReader("input.txt"));
     BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
     for (String line; (line = br.readLine()) != null; ) {
       bw.write(line);
       bw.newLine();
     }
     br.close();
     bw.close();
   }
 }

mIRC Scripting Language

Interpreter: mIRC

 alias Write2FileAndReadIt {
 .write myfilename.txt Goodbye Mike!
 .echo -a Myfilename.txt contains: $read(myfilename.txt,1)
 }

Objective C

Compiler: gcc

There are various classes in Objective C for opening, reading, and writing files. One way is with the NSFileManager class for reading, and a NSFileHandle for writing.

 NSString *inputPath = @"input.txt";
 NSString *outputPath = @"output.txt";
 
 if( [[NSFileManager defaultManager] isReadableFileAtPath:inputPath] ){
   NSData *data = [[NSFileManager defaultManager] contentsAtPath:inputPath];
   [[NSFileManager defaultManager] createFileAtPath:outputPath contents:data attributes:nil];
 } else {
   NSLog( @"No such file." );
 }

Perl

Interpreter: Perl 5.8.8

#!/usr/bin/perl

open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!";
open my $fh_out, '>', 'output.txt' or die "could not open <output.txt> for writing: $!";
# '>' overwrites file, '>>' appends to file, just like in the shell

binmode $fh_out; # marks filehandle for binary content on systems where that matters

print $fh_out $_ while <$fh_in>;
# prints current line to file associated with $fh_out filehandle

# the same, less concise
#while (<$fh_in>) {
#  print $fh_out $_;
#};

close $fh_in;
close $fh_out;

Perl has also a powerful mechanism in conjunction with opening files called IO disciplines. It allows you to automatically apply chainable transformations on the input and output. Mangling newlines, gzip (de)compression and character encoding are the most used examples.

PHP

Interpreter: PHP 4

 <?php
 
 if (!$in=fopen('input.txt','r')) {
 	die('Could not open input.txt!');
 }
 
 if (!$out=fopen('output.txt','w')) {
 	die('Could not open output.txt!');
 }
 
 while(!feof($in)) {
 	$data = fread($in,512);
 	fwrite($out,$data);
 }
 
 fclose($out);
 fclose($in);
 ?>
 

Interpreter: PHP 5

 <?php
 if( $contents = file_get_contents('input.txt') ){
 	if( !file_put_contents('output.txt') ) echo('could not write output file');
 }else{
 	echo('could not open input file');
 }
 ?>

Python

Interpreter: Python 2.4

In short form:

 open("output.txt", "w").writelines(open("input.txt"))

With proper closing:

inputFile = open("input.txt","r")
try:
  outputFile = open("output.txt", "w")
  try:
    outputFile.writelines(inputFile)
  finally:
    outputFile.close()
finally:
  inputFile.close()

Interpreter: Python 2.5

Using the new with statement for automatic closing even in case of error:

from __future__ import with_statement
from contextlib import nested

try:
    with nested(file("input.txt"), file("output.txt", "w")) as (
            input_file, output_file):
        output_file.writelines(input_file)
except IOError, e:
    print e

Ruby

Interpreter: Ruby 1.8.4

begin
  File.open("output.txt","w") {|f| f << IO.read("input.txt")}
rescue Exception => e
  $stderr.puts "Exception raised: #{e}"
end

TCL

Interpreter: tclsh, eTcl, wish, tixwish

set in [open "input.txt" r]
set out [open "output.txt" w]
puts -nonewline $out [read $in]
close $in
close $out
#or the minimal version if we don't need any processing of the data
file copy input.txt output.txt

Other File I/O:

#open file for writing
set myfile [open "README.TXT" w]
#write something to the file
puts $myfile "This is line 1, so hello world...."
#close the file
close $myfile


#open file for reading
set myfile [open "README.TXT" r]
#read something from the file
gets $myfile mydata
#show what was read from the file
#should print "This is line1, so hello world...."
puts $mydata
#close the file
close $myfile

UNIX Shell

Interpreter: Bourne Shell Operating System: UNIX

#!/bin/sh
while read a; do
    echo "$a"
done <input.txt >output.txt

Another way, using the 'cat' program

#!/bin/sh
cat input.txt >output.txt

Yet another way, using the 'cp' utility

#!/bin/sh
cp input.txt output.txt