File input/output: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎[[C++]]: Fixed link)
Line 21: Line 21:
Close (Output);
Close (Output);
end File_IO;
end File_IO;

==[[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]]==
==[[C]]==

Revision as of 06:31, 23 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;

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;
}

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));
 }

Java

Compiler: GCJ 4.1.2

Simple version; files are closed by OS when the program finishes

[EDIT: Are you sure they automatically close? I read nothing in the standard API to that effect.]

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
    }
  }
}

This version uses the newer (1.4 onwards) nio package.

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
    }
  }
}

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');
 }
 ?>

mIRC

Compiler: mIRC

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

Python

Interpreter: Python 2.4

In short form:

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

With proper closing and exception-handling:

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

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

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
#!/bin/sh
# another way, using the 'cat' program
cat input.txt >output.txt
# yet another way, using the 'cp' utility
cp input.txt output.txt