Create a file on magnetic tape: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|C}}: Remove vanity tags)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(28 intermediate revisions by 16 users not shown)
Line 3: Line 3:
{{omit from|AWK|not OO}}
{{omit from|AWK|not OO}}
{{omit from|BASIC|not OO}}
{{omit from|BASIC|not OO}}
{{omit from|C sharp}}
{{omit from|Fortran|not OO}}
{{omit from|Fortran|not OO}}
{{omit from|GUISS}}
{{omit from|GUISS}}
Line 14: Line 15:
{{omit from|Retro}}
{{omit from|Retro}}
{{omit from|TI-89 BASIC}}
{{omit from|TI-89 BASIC}}
{{omit from|Visual Basic .NET}}
{{omit from|zkl}}
{{omit from|zkl}}


The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.

=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Save(CHAR ARRAY text)
BYTE dev=[1]

Close(dev)
Open(dev,"C:",8,128)
PrintE("Saving started...")
PrintF("Saving text: ""%S""%E",text)
PrintD(dev,text)
Close(dev)
PrintE("Saving finished.")
RETURN

PROC Load()
CHAR ARRAY result(255)
BYTE dev=[1]

Close(dev)
Open(dev,"C:",4,128)
PrintE("Loading started...")
WHILE Eof(dev)=0
DO
InputSD(dev,result)
PrintF("Loading text: ""%S""%E",result)
OD
Close(dev)
PrintE("Loading finished.")
RETURN

PROC Main()
BYTE CH=$02FC ;Internal hardware value for last key pressed

PrintE("Press any key to save a file on tape.")
Save("Atari Action!")

PutE()
PrintE("Rewind the tape and press any key to load previously saved file from tape.")
Load()
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Create_a_file_on_magnetic_tape.png Screenshot from Atari 8-bit computer]
<pre>
Press any key to save a file on tape.
Saving started...
Saving text: "Atari Action!"
Saving finished.

Rewind the tape and press any key to load previously saved file from tape.
Loading started...
Loading text: "Atari Action"
Loading finished.
</pre>


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<lang ApplesoftBasic>SAVE</lang>
<syntaxhighlight lang="applesoftbasic">SAVE</syntaxhighlight>

=={{header|Arturo}}==

<syntaxhighlight lang="rebol">write "TAPE.FILE" {
This code
should be able to write
a file
to magnetic tape
}</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
The program is self explanatory. :)
The program is self explanatory. :)
<syntaxhighlight lang="c">
<lang C>
#include<stdio.h>
#include<stdio.h>


Line 44: Line 108:
}
}


</syntaxhighlight>
</lang>

=={{header|C++}}==
{{trans|D}}
<syntaxhighlight lang="cpp">#include <iostream>
#include <fstream>

#if defined(_WIN32) || defined(WIN32)
constexpr auto FILENAME = "tape.file";
#else
constexpr auto FILENAME = "/dev/tape";
#endif

int main() {
std::filebuf fb;
fb.open(FILENAME,std::ios::out);
std::ostream os(&fb);
os << "Hello World\n";
fb.close();
return 0;
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(spit "/dev/tape" "Hello, World!")</lang>
<syntaxhighlight lang="clojure">(spit "/dev/tape" "Hello, World!")</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==


{{works with|OpenCOBOL}}
{{works with|COBOL 2002}}


<lang COBOL> >>SOURCE FORMAT IS FREE
<syntaxhighlight lang="cobolfree"> >>SOURCE FORMAT IS FREE
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. MAKE-TAPE-FILE.
PROGRAM-ID. MAKE-TAPE-FILE.
Line 61: Line 145:
FILE-CONTROL.
FILE-CONTROL.
SELECT TAPE-FILE
SELECT TAPE-FILE
ASSIGN "./TAPE.FILE"
ASSIGN TO "./TAPE.FILE"
ORGANIZATION IS LINE SEQUENTIAL.
ORGANIZATION IS SEQUENTIAL
ACCESS MODE IS SEQUENTIAL.


DATA DIVISION.
DATA DIVISION.
FILE SECTION.
FILE SECTION.
FD TAPE-FILE.
FD TAPE-FILE RECORD CONTAINS 51 CHARACTERS.
01 TAPE-FILE-RECORD PIC X(51).
01 TAPE-FILE-RECORD PICTURE IS X(51).


PROCEDURE DIVISION.
PROCEDURE DIVISION.
Line 74: Line 159:
FROM "COBOL treats tape files and text files identically."
FROM "COBOL treats tape files and text files identically."
END-WRITE
END-WRITE
STOP RUN.</lang>
CLOSE TAPE-FILE
STOP RUN.

END PROGRAM MAKE-TAPE-FILE.</syntaxhighlight>

=={{header|Crystal}}==
{{trans|D}}
<syntaxhighlight lang="ruby">filename = {% if flag?(:win32) %}
"TAPE.FILE"
{% else %}
"/dev/tape"
{% end %}
File.write filename, "howdy, planet!"</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang D>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void main() {
void main() {
Line 86: Line 183:
}
}
f.writeln("Hello World!");
f.writeln("Hello World!");
}</lang>
}</syntaxhighlight>

=={{header|Delphi}}==
{{Trans|D}}
<syntaxhighlight lang="delphi">
program Create_a_file_on_magnetic_tape;

{$APPTYPE CONSOLE}

const
{$IFDEF WIN32}
FileName = 'tape.file';
{$ELSE}
FileName = '/dev/tape';
{$ENDIF}

var
f: TextFile;

begin
Assign(f, FileName);
Rewrite(f);
Writeln(f, 'Hello World');
close(f);
end.
</syntaxhighlight>

=={{header|F#}}==
<syntaxhighlight lang="fsharp">
open System
open System.IO

let env = Environment.OSVersion.Platform
let msg = "Hello Rosetta!"

match env with
| PlatformID.Win32NT | PlatformID.Win32S | PlatformID.Win32Windows | PlatformID.WinCE -> File.WriteAllText("TAPE.FILE", msg)
| _ -> File.WriteAllText("/dev/tape", msg)
</syntaxhighlight>

=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: io.encodings.ascii io.files kernel system ;

"Hello from Rosetta Code!"
os windows? "tape.file" "/dev/tape" ?
ascii set-file-contents</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 97: Line 239:
This was developed when tape drives used half-inch tapes in lengths up to 2,400 feet and seven or nine-track recording, storing up to about 150MB per reel - much depended on the length lost to IRG usage between blocks, but block sizes beyond 20,000 were considered large. Subsequent tape designs have included 18, 36, and 128 tracks, helical recording and storage capacities in tens of gigabytes. Naturally, the tape labelling protocols have become even more complex, but, these matters are handled by more complex operating systems.
This was developed when tape drives used half-inch tapes in lengths up to 2,400 feet and seven or nine-track recording, storing up to about 150MB per reel - much depended on the length lost to IRG usage between blocks, but block sizes beyond 20,000 were considered large. Subsequent tape designs have included 18, 36, and 128 tracks, helical recording and storage capacities in tens of gigabytes. Naturally, the tape labelling protocols have become even more complex, but, these matters are handled by more complex operating systems.



=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Dim As Integer numarch = Freefile
Open "tape.file" For Output As #numarch
Print #numarch, "Soy un archivo de cinta ahora, o espero serlo pronto."
Close #numarch</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Line 105: Line 253:
The tar archive will contain a single file, called <tt>TAPE.FILE</tt> by default,
The tar archive will contain a single file, called <tt>TAPE.FILE</tt> by default,
with the contents of the command line <tt>-data</tt> option.
with the contents of the command line <tt>-data</tt> option.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 157: Line 305:
log.Fatal("writing data:", err)
log.Fatal("writing data:", err)
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
% go run tapefile.go -data "Hello World" -gzip | tar -tvzf -
% go run tapefile.go -data "Hello World" -gzip | tar -tvzf -
-rw-rw---- 0 guest guest 11 11 Aug 13:42 TAPE.FILE</pre>
-rw-rw---- 0 guest guest 11 11 Aug 13:42 TAPE.FILE</pre>

=={{header|Groovy}}==
{{trans|Java}}
<syntaxhighlight lang="groovy">import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths

class CreateFile {
static void main(String[] args) throws IOException {
String os = System.getProperty("os.name")
if (os.contains("Windows")) {
Path path = Paths.get("tape.file")
Files.write(path, Collections.singletonList("Hello World!"))
} else {
Path path = Paths.get("/dev/tape")
Files.write(path, Collections.singletonList("Hello World!"))
}
}
}</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==


<lang haskell>module Main (main) where
<syntaxhighlight lang="haskell">module Main (main) where


main :: IO ()
main :: IO ()
main = writeFile "/dev/tape" "Hello from Rosetta Code!"</lang>
main = writeFile "/dev/tape" "Hello from Rosetta Code!"</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==


This solution mimics the solution used in many other languages here and works in both Icon and Unicon.
This solution mimics the solution used in many other languages here and works in both Icon and Unicon.
<lang unicon>procedure main()
<syntaxhighlight lang="unicon">procedure main()
write(open("/dev/tape","w"),"Hi")
write(open("/dev/tape","w"),"Hi")
end</lang>
end</syntaxhighlight>

=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 OPEN #1:"Tape1:README.TXT" ACCESS OUTPUT
110 PRINT #1:"I am a tape file now, or hope to be soon."
120 CLOSE #1</syntaxhighlight>

=={{header|Java}}==
<syntaxhighlight lang="java">import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;

public class CreateFile {
public static void main(String[] args) throws IOException {
String os = System.getProperty("os.name");
if (os.contains("Windows")) {
Path path = Paths.get("tape.file");
Files.write(path, Collections.singletonList("Hello World!"));
} else {
Path path = Paths.get("/dev/tape");
Files.write(path, Collections.singletonList("Hello World!"));
}
}
}</syntaxhighlight>


=={{header|JCL}}==
=={{header|JCL}}==
<lang JCL>// EXEC PGM=IEBGENER
<syntaxhighlight lang="jcl">// EXEC PGM=IEBGENER
//* Create a file named "TAPE.FILE" on magnetic tape; "UNIT=TAPE"
//* Create a file named "TAPE.FILE" on magnetic tape; "UNIT=TAPE"
//* may vary depending on site-specific esoteric name assignment
//* may vary depending on site-specific esoteric name assignment
Line 186: Line 378:
//SYSUT1 DD *
//SYSUT1 DD *
DATA TO BE WRITTEN TO TAPE
DATA TO BE WRITTEN TO TAPE
/* </lang>
/* </syntaxhighlight>

=={{header|Julia}}==
<syntaxhighlight lang="julia">
open("/dev/tape", "w") do f
write(f, "Hello tape!")
end
</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Scala}}
{{trans|Scala}}
<lang scala>// version 1.1.0 (Linux)
<syntaxhighlight lang="scala">// version 1.1.0 (Linux)


import java.io.FileWriter
import java.io.FileWriter
Line 198: Line 397:
lp0.write("Hello, world!")
lp0.write("Hello, world!")
lp0.close()
lp0.close()
}</lang>
}</syntaxhighlight>

=={{header|Lua}}==
<syntaxhighlight lang="lua">require "lfs"

local out
if lfs.attributes('/dev/tape') then
out = '/dev/tape'
else
out = 'tape.file'
end
file = io.open(out, 'w')
file:write('Hello world')
io.close(file)</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>var t = open("/dev/tape", fmWrite)
<syntaxhighlight lang="nim">var t = open("/dev/tape", fmWrite)
t.writeln "Hi Tape!"
t.writeln "Hi Tape!"
t.close</lang>
t.close</syntaxhighlight>


=={{header|Perl 6}}==
=={{header|Phix}}==
<syntaxhighlight lang="phix">include builtins/write_file.e
<lang perl6>my $tape = open "/dev/tape", :w or die "Can't open tape: $!";
constant filepath = iff(platform()=WINDOWS?"tape.file":"/dev/tape"),
$tape.say: "I am a tape file now, or hope to be soon.";
write_file(file_path,"Hello world!")</syntaxhighlight>
$tape.close;</lang>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(out "/dev/tape"
<syntaxhighlight lang="picolisp">(out "/dev/tape"
(prin "Hello World!") )</lang>
(prin "Hello World!") )</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>>>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n')
<syntaxhighlight lang="python">>>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n')
...
...
>>> </lang>
>>> </syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket
(with-output-to-file "/dev/tape" #:exists 'append
(with-output-to-file "/dev/tape" #:exists 'append
(λ() (displayln "I am a cheap imitation of the Perl code for a boring problem")))
(λ() (displayln "I am a cheap imitation of the Perl code for a boring problem")))
</syntaxhighlight>
</lang>

=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>my $tape = open "/dev/tape", :w or die "Can't open tape: $!";
$tape.say: "I am a tape file now, or hope to be soon.";
$tape.close;</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 232: Line 450:
<br><br>VM/CMS would use a &nbsp; '''CP ATTACH''' &nbsp; command, coupled with a &nbsp; '''CMS FILEDEF''' &nbsp; command which associates a
<br><br>VM/CMS would use a &nbsp; '''CP ATTACH''' &nbsp; command, coupled with a &nbsp; '''CMS FILEDEF''' &nbsp; command which associates a
<br>DSNAME &nbsp; (dataset name) &nbsp; that will be written to on the attached (and mounted) magnetic tape device.
<br>DSNAME &nbsp; (dataset name) &nbsp; that will be written to on the attached (and mounted) magnetic tape device.
<lang rexx>/*REXX pgm demonstrates writing records to an attached magnetic tape.*/
<syntaxhighlight lang="rexx">/*REXX pgm demonstrates writing records to an attached magnetic tape.*/
dsName = 'TAPE.FILE' /*dsName of "file" being written.*/
dsName = 'TAPE.FILE' /*dsName of "file" being written.*/


Line 238: Line 456:
call lineout dsName, 'this is record' j || "."
call lineout dsName, 'this is record' j || "."
end /*j*/
end /*j*/
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Create a file on magnetic tape
# Project : Create a file on magnetic tape


Line 249: Line 467:
fwrite(fp, str)
fwrite(fp, str)
fclose(fp)
fclose(fp)
</syntaxhighlight>
</lang>

=={{header|Ruby}}==
{{trans|C}}
<syntaxhighlight lang="ruby">File.open("tape.file", "w") do |fh|
fh.syswrite("This code should be able to write a file to magnetic tape.\n")
end</syntaxhighlight>

=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::io::Write;
use std::fs::File;

fn main() -> std::io::Result<()> {
File::open("/dev/tape")?.write_all(b"Hello from Rosetta Code!")
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
===[[Unix]]===
===[[Unix]]===
Assuming device is attached to "tape"
Assuming device is attached to "tape"
<lang Scala>object LinePrinter extends App {
<syntaxhighlight lang="scala">object LinePrinter extends App {
import java.io.{ FileWriter, IOException }
import java.io.{ FileWriter, IOException }
{
{
Line 261: Line 493:
lp0.close()
lp0.close()
}
}
}</lang>
}</syntaxhighlight>

=={{header|Seed7}}==

<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";

const proc: main is func
local
var file: tapeFile is STD_NULL;
begin
tapeFile := open("/dev/tape", "w");
if tapeFile = STD_NULL then
tapeFile := open("tape.file", "w");
end if;
if tapeFile <> STD_NULL then
writeln(tapeFile, "Hello, world!");
close(tapeFile);
else
writeln(" ***** Cannot open tape file.");
end if;
end func;</syntaxhighlight>

=={{header|Tcl}}==
=={{header|Tcl}}==
Tcl does not have built-in special support for tape devices, so it relies on the OS to handle most of the details for it. Assuming a relatively modern Unix:
Tcl does not have built-in special support for tape devices, so it relies on the OS to handle most of the details for it. Assuming a relatively modern Unix:
{{trans|UNIX Shell}}
{{trans|UNIX Shell}}
<lang tcl>cd /tmp
<syntaxhighlight lang="tcl">cd /tmp


# Create the file
# Create the file
Line 277: Line 530:
fcopy $fin $fout
fcopy $fin $fout
close $fin
close $fin
close $fout</lang>
close $fout</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>$$ MODE TUSCRIPT
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
STATUS = CREATE ("tape.file",tape-o,-std-)
STATUS = CREATE ("tape.file",tape-o,-std-)
PRINT STATUS</lang>
PRINT STATUS</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 289: Line 542:


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang bash>#!/bin/sh
<syntaxhighlight lang="bash">#!/bin/sh
cd # Make our home directory current
cd # Make our home directory current
echo "Hello World!" > hello.jnk # Create a junk file
echo "Hello World!" > hello.jnk # Create a junk file
# tape rewind # Uncomment this to rewind the tape
# tape rewind # Uncomment this to rewind the tape
tar c hello.jnk # Traditional archivers use magnetic tape by default
tar c hello.jnk # Traditional archivers use magnetic tape by default
# tar c hello.jnk > /dev/tape # With newer archivers redirection is needed</lang>
# tar c hello.jnk > /dev/tape # With newer archivers redirection is needed</syntaxhighlight>

=={{header|Wren}}==
<syntaxhighlight lang="wren">import "os" for Platform
import "io" for File

var fileName = (Platform.isWindows) ? "TAPE.FILE" : "/dev/tape"
File.create(fileName) { |file|
file.writeBytes("Hello World!\n")
}</syntaxhighlight>


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
Line 301: Line 563:
We can use any start address, depending on where we want the data to come from.
We can use any start address, depending on where we want the data to come from.
Here we dump the contents of the screen:
Here we dump the contents of the screen:
<lang zxbasic>SAVE "TAPEFILE" CODE 16384,6912</lang>
<syntaxhighlight lang="zxbasic">SAVE "TAPEFILE" CODE 16384,6912</syntaxhighlight>

{{omit from|C sharp}}

Latest revision as of 12:26, 21 November 2023

Task
Create a file on magnetic tape
You are encouraged to solve this task according to the task description, using any language you may know.

The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.

Action!

PROC Save(CHAR ARRAY text)
  BYTE dev=[1]

  Close(dev)
  Open(dev,"C:",8,128)
  PrintE("Saving started...")
  PrintF("Saving text: ""%S""%E",text)
  PrintD(dev,text)
  Close(dev)
  PrintE("Saving finished.")
RETURN

PROC Load()
  CHAR ARRAY result(255)
  BYTE dev=[1]

  Close(dev)
  Open(dev,"C:",4,128)
  PrintE("Loading started...")
  WHILE Eof(dev)=0
  DO
    InputSD(dev,result)
    PrintF("Loading text: ""%S""%E",result)
  OD
  Close(dev)
  PrintE("Loading finished.")
RETURN

PROC Main()
  BYTE CH=$02FC ;Internal hardware value for last key pressed

  PrintE("Press any key to save a file on tape.")
  Save("Atari Action!")

  PutE()
  PrintE("Rewind the tape and press any key to load previously saved file from tape.")
  Load()
RETURN
Output:

Screenshot from Atari 8-bit computer

Press any key to save a file on tape.
Saving started...
Saving text: "Atari Action!"
Saving finished.

Rewind the tape and press any key to load previously saved file from tape.
Loading started...
Loading text: "Atari Action"
Loading finished.

Applesoft BASIC

SAVE

Arturo

write "TAPE.FILE" {
    This code 
    should be able to write 
    a file 
    to magnetic tape
}

C

The program is self explanatory. :)

#include<stdio.h>

int main()
{
	FILE* fp = fopen("TAPE.FILE","w");
	
	fprintf(fp,"This code should be able to write a file to magnetic tape.\n");
	fprintf(fp,"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\n");
	fprintf(fp,"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\n");
	fprintf(fp,"And since C is already 44, maybe 45, years old in 2017, I am sure someone somewhere did use a C compiler on magnetic tapes.\n");
	fprintf(fp,"If you happen to have one, please try to compile and execute me on that system.\n");
	fprintf(fp,"My creator tested me on an i5 machine with SSD and RAM that couldn't have even been dreamt of by Denis Ritchie.\n");
	fprintf(fp,"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\n");
	fprintf(fp,"EOF");
	
	fclose(fp);
	
	return 0;
}

C++

Translation of: D
#include <iostream>
#include <fstream>

#if defined(_WIN32) || defined(WIN32)
constexpr auto FILENAME = "tape.file";
#else
constexpr auto FILENAME = "/dev/tape";
#endif

int main() {
    std::filebuf fb;
    fb.open(FILENAME,std::ios::out);
    std::ostream os(&fb);
    os << "Hello World\n";
    fb.close();
    return 0;
}

Clojure

(spit "/dev/tape" "Hello, World!")

COBOL

Works with: COBOL 2002
       >>SOURCE FORMAT IS FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. MAKE-TAPE-FILE.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT TAPE-FILE
        ASSIGN TO "./TAPE.FILE"
        ORGANIZATION IS SEQUENTIAL
        ACCESS MODE IS SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD  TAPE-FILE RECORD CONTAINS 51 CHARACTERS.
01  TAPE-FILE-RECORD PICTURE IS X(51).

PROCEDURE DIVISION.
    OPEN OUTPUT SHARING WITH ALL OTHER TAPE-FILE
    WRITE TAPE-FILE-RECORD 
        FROM "COBOL treats tape files and text files identically."
    END-WRITE
    CLOSE TAPE-FILE
    STOP RUN.

END PROGRAM MAKE-TAPE-FILE.

Crystal

Translation of: D
filename = {% if flag?(:win32) %}
    "TAPE.FILE"
  {% else %}   
    "/dev/tape"
  {% end %}        
File.write filename, "howdy, planet!"

D

import std.stdio;

void main() {
    version(Windows) {
        File f = File("TAPE.FILE", "w");
    } else {
        File f = File("/dev/tape", "w");
    }
    f.writeln("Hello World!");
}

Delphi

Translation of: D
program Create_a_file_on_magnetic_tape;

{$APPTYPE CONSOLE}

const
{$IFDEF WIN32}
  FileName = 'tape.file';
{$ELSE}
  FileName = '/dev/tape';
{$ENDIF}

var
  f: TextFile;

begin
  Assign(f, FileName);
  Rewrite(f);
  Writeln(f, 'Hello World');
  close(f);
end.

F#

open System
open System.IO

let env = Environment.OSVersion.Platform
let msg = "Hello Rosetta!"

match env with
    | PlatformID.Win32NT | PlatformID.Win32S | PlatformID.Win32Windows | PlatformID.WinCE -> File.WriteAllText("TAPE.FILE", msg)
    | _ -> File.WriteAllText("/dev/tape", msg)

Factor

USING: io.encodings.ascii io.files kernel system ;

"Hello from Rosetta Code!"
os windows? "tape.file" "/dev/tape" ?
ascii set-file-contents

Fortran

Fortran performs reads and writes to some device, without caring much about the precise nature of the device: card reader/punch, paper tape reader/punch, keyboard, display console, and of course magnetic tape. Sequential input or output is normal, but random access by record number is also possible, though the interface between the Fortran program and the device may not support such attempts, as with a card reader or a display screen. There are also special statements, such as REWIND and BACKSPACE, and ENDFILE. The file OPEN statement will specify such matters as record length and block size and so all is in place for dealing with magnetic tapes...

Of the simplest sort: "Unlabelled". Such a tape consists of a sequence of data blocks, separated by inter-record-gaps, with two in a row at the end to specify the end-of-data on the tape. Although called inter-record, they are actually inter-block: the tape unit reads or writes blocks of say 5,000 characters, not caring that each block might be regarded as containing 50 records of length 100, or 100 records of length 50, etc. The inter-record gap is a sequence of three quarters of an inch of magnetic tape, containing special magnetisation that can be written or sensed at any speed, because these spaces are where the tape is brought to rest between reads or writes. That is, having written the data of a block at full speed, the tape write head writes an IRG as the tape is brought to a stop, and later, when it resumes motion to reach operating speed for the writing of the next block. With adequate data buffering, tape is moved past the head without pause through the IRG as blocks are read or written. If the tape is being read (and written!) with random access the width of the IRG allows for some slop in positioning. Some caution is in order: a "fast forward" action, followed by a few seconds pause to allow the attainment of maximum speed, then a REWIND resulted in a piece of tape being stretched to double length and half width...

Unlabelled tapes are quite inconvenient in a non-user operated computer installation, as mistakes are very easy to make. The wrong tape gets overwritten and the ensuing conversation sours. Computer-readable labels were introduced to supplement human-readable written labels affixed to the tape reel. Co-ordination and standardisation were weak in the 1970s, so there was a lot of variation and partial interoperability between manufacturers and ANSI standards. The first step was of course non-standard labels: some data would be written to the start of the tape that constituted a label, followed by a tape mark, then the actual data file, and so on. Users at an installation would attempt to conform to the local style, and there would be discussions, especially when tapes were exchanged with different systems. A large organisation such as IBM would have its method, and the basic idea was that at the start of the tape would be a volume label and additional information to allow for a data file (or multiple data files) that extended over many reels of tape, each tape identified in turn. This would start with an eighty-character record, beginning "VOL1" - but in EBCDIC, and only later in ASCII. None of this would be visible to the user's programme because it would be handled by the operating system with statements in Job Control Language for the run to identify the file on tape that is to be accessed when the user's programme executes an OPEN statement of a suitable form. And this access would revert to sequential reading or writing with quite ordinary READ and WRITE statements.

This was developed when tape drives used half-inch tapes in lengths up to 2,400 feet and seven or nine-track recording, storing up to about 150MB per reel - much depended on the length lost to IRG usage between blocks, but block sizes beyond 20,000 were considered large. Subsequent tape designs have included 18, 36, and 128 tracks, helical recording and storage capacities in tens of gigabytes. Naturally, the tape labelling protocols have become even more complex, but, these matters are handled by more complex operating systems.


FreeBASIC

Dim As Integer numarch = Freefile
Open "tape.file" For Output As #numarch
Print #numarch, "Soy un archivo de cinta ahora, o espero serlo pronto."
Close #numarch

Go

Taking a cue from the discussion page, this creates an optionally compressed tar (tape archive) file on stdout (or written to a file or a device such as /dev/tape). The tar archive will contain a single file, called TAPE.FILE by default, with the contents of the command line -data option.

package main

import (
        "archive/tar"
        "compress/gzip"
        "flag"
        "io"
        "log"
        "os"
        "time"
)

func main() {
        filename := flag.String("file", "TAPE.FILE", "filename within TAR")
        data := flag.String("data", "", "data for file")
        outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)")
        gzipFlag := flag.Bool("gzip", false, "use gzip compression")
        flag.Parse()

        var w io.Writer = os.Stdout
        if *outfile != "" {
                f, err := os.Create(*outfile)
                if err != nil {
                        log.Fatalf("opening/creating %q: %v", *outfile, err)
                }
                defer f.Close()
                w = f
        }

        if *gzipFlag {
                zw := gzip.NewWriter(w)
                defer zw.Close()
                w = zw
        }

        tw := tar.NewWriter(w)
        defer tw.Close()
        w = tw
        tw.WriteHeader(&tar.Header{
                Name:     *filename,
                Mode:     0660,
                Size:     int64(len(*data)),
                ModTime:  time.Now(),
                Typeflag: tar.TypeReg,
                Uname:    "guest",
                Gname:    "guest",
        })

        _, err := w.Write([]byte(*data))
        if err != nil {
                log.Fatal("writing data:", err)
        }
}
Output:
% go run tapefile.go -data "Hello World" -gzip | tar -tvzf -
-rw-rw----  0 guest  guest      11 11 Aug 13:42 TAPE.FILE

Groovy

Translation of: Java
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths

class CreateFile {
    static void main(String[] args) throws IOException {
        String os = System.getProperty("os.name")
        if (os.contains("Windows")) {
            Path path = Paths.get("tape.file")
            Files.write(path, Collections.singletonList("Hello World!"))
        } else {
            Path path = Paths.get("/dev/tape")
            Files.write(path, Collections.singletonList("Hello World!"))
        }
    }
}

Haskell

module Main (main) where

main :: IO ()
main = writeFile "/dev/tape" "Hello from Rosetta Code!"

Icon and Unicon

This solution mimics the solution used in many other languages here and works in both Icon and Unicon.

procedure main()
    write(open("/dev/tape","w"),"Hi")
end

IS-BASIC

100 OPEN #1:"Tape1:README.TXT" ACCESS OUTPUT
110 PRINT #1:"I am a tape file now, or hope to be soon."
120 CLOSE #1

Java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;

public class CreateFile {
    public static void main(String[] args) throws IOException {
        String os = System.getProperty("os.name");
        if (os.contains("Windows")) {
            Path path = Paths.get("tape.file");
            Files.write(path, Collections.singletonList("Hello World!"));
        } else {
            Path path = Paths.get("/dev/tape");
            Files.write(path, Collections.singletonList("Hello World!"));
        }
    }
}

JCL

// EXEC PGM=IEBGENER 
//* Create a file named "TAPE.FILE" on magnetic tape; "UNIT=TAPE" 
//*    may vary depending on site-specific esoteric name assignment 
//SYSPRINT DD SYSOUT=* 
//SYSIN    DD DUMMY 
//SYSUT2   DD UNIT=TAPE,DSN=TAPE.FILE,DISP=(,CATLG) 
//SYSUT1   DD * 
DATA TO BE WRITTEN TO TAPE 
/*

Julia

open("/dev/tape", "w") do f
    write(f, "Hello tape!")
end

Kotlin

Translation of: Scala
// version 1.1.0 (Linux)

import java.io.FileWriter

fun main(args: Array<String>) {
    val lp0 = FileWriter("/dev/tape")
    lp0.write("Hello, world!")
    lp0.close()
}

Lua

require "lfs"

local out
if lfs.attributes('/dev/tape') then
    out = '/dev/tape'
else
    out = 'tape.file'
end
file = io.open(out, 'w')
file:write('Hello world')
io.close(file)

Nim

var t = open("/dev/tape", fmWrite)
t.writeln "Hi Tape!"
t.close

Phix

include builtins/write_file.e
constant filepath = iff(platform()=WINDOWS?"tape.file":"/dev/tape"),
write_file(file_path,"Hello world!")

PicoLisp

(out "/dev/tape"
   (prin "Hello World!") )

Python

>>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n')
... 
>>>

Racket

#lang racket
(with-output-to-file "/dev/tape" #:exists 'append
  (λ() (displayln "I am a cheap imitation of the Perl code for a boring problem")))

Raku

(formerly Perl 6)

my $tape = open "/dev/tape", :w or die "Can't open tape: $!";
$tape.say: "I am a tape file now, or hope to be soon.";
$tape.close;

REXX

The actual mounting and attaching would be performed by the appropriate operating system (and/or user) commands.

DSNAME   (below)   would be the REXX variable that is associated with a dataset that is assigned to a magnetic tape
device.   The association would be different, depending on upon the operating system being used.

VM/CMS would use a   CP ATTACH   command, coupled with a   CMS FILEDEF   command which associates a
DSNAME   (dataset name)   that will be written to on the attached (and mounted) magnetic tape device.

/*REXX pgm  demonstrates  writing records  to an attached magnetic tape.*/
dsName = 'TAPE.FILE'                   /*dsName of "file" being written.*/

          do j=1  for 100              /*write 100 records to mag tape. */
          call lineout  dsName,  'this is record'   j   ||   "."
          end   /*j*/
                                       /*stick a fork in it, we're done.*/

Ring

# Project : Create a file on magnetic tape

fn = "Tape.file"
fp = fopen(fn,"w")
str = "I am a tape file now, or hope to be soon."
fwrite(fp, str)
fclose(fp)

Ruby

Translation of: C
File.open("tape.file", "w") do |fh|
    fh.syswrite("This code should be able to write a file to magnetic tape.\n")
end

Rust

use std::io::Write;
use std::fs::File;

fn main() -> std::io::Result<()> {
    File::open("/dev/tape")?.write_all(b"Hello from Rosetta Code!")
}

Scala

Unix

Assuming device is attached to "tape"

object LinePrinter extends App {
  import java.io.{ FileWriter, IOException }
  {
    val lp0 = new FileWriter("/dev/tape")
    lp0.write("Hello, world!")
    lp0.close()
  }
}

Seed7

$ include "seed7_05.s7i";

const proc: main is func
  local
    var file: tapeFile is STD_NULL;
  begin
    tapeFile := open("/dev/tape", "w");
    if tapeFile = STD_NULL then
      tapeFile := open("tape.file", "w");
    end if;
    if tapeFile <> STD_NULL then
      writeln(tapeFile, "Hello, world!");
      close(tapeFile);
    else
      writeln(" ***** Cannot open tape file.");
    end if;
  end func;

Tcl

Tcl does not have built-in special support for tape devices, so it relies on the OS to handle most of the details for it. Assuming a relatively modern Unix:

Translation of: UNIX Shell
cd /tmp

# Create the file
set f [open hello.jnk w]
puts $f "Hello World!"
close $f

# Archive to tape
set fin [open "|tar cf - hello.jnk" rb]
set fout [open /dev/tape wb]
fcopy $fin $fout
close $fin
close $fout

TUSCRIPT

$$ MODE TUSCRIPT
STATUS = CREATE ("tape.file",tape-o,-std-)
PRINT STATUS
Output:
OK

UNIX Shell

#!/bin/sh
cd    # Make our home directory current
echo "Hello World!" > hello.jnk  # Create a junk file
# tape rewind                    # Uncomment this to rewind the tape
tar c hello.jnk                  # Traditional archivers use magnetic tape by default
# tar c hello.jnk > /dev/tape    # With newer archivers redirection is needed

Wren

import "os" for Platform
import "io" for File

var fileName = (Platform.isWindows) ? "TAPE.FILE" : "/dev/tape"
File.create(fileName) { |file|
    file.writeBytes("Hello World!\n")
}

ZX Spectrum Basic

The ZX Spectrum does not have file type extensions, so we save as TAPEFILE, rather than TAPE.FILE. We can use any start address, depending on where we want the data to come from. Here we dump the contents of the screen:

SAVE "TAPEFILE" CODE 16384,6912