File I/O in Every Programming Language

This has to be a common question that all programmers have from time to time. How do I read a line from a text file? Then the next question is always how do i write it back.

Of course most of you use a high level framework in day to day programming (which are fine to use in answers) but sometimes it's nice to know how to do it at a low level too.

I myself know how to do it in C, C++ and Objective-C, but it sure would be handy to see how it's done in all of the popular languages, if only to help us make a better decision about what language to do our file io in. In particular I think it would be interesting to see how its done in the string manipulation languages, like: python, ruby and of course perl.

So I figure here we can create a community resource that we can all star to our profiles and refer to when we need to do file I/O in some new language. Not to mention the exposure we will all get to languages that we don't deal with on a day to day basis.

This is how you need to answer:

  1. Create a new text file called "fileio.txt"
  2. Write the first line "hello" to the text file.
  3. Append the second line "world" to the text file.
  4. Read the second line "world" into an input string.
  5. Print the input string to the console.

Clarification:

  • You should show how to do this in one programming language per answer only.
  • Assume that the text file doesn't exist beforehand
  • You don't need to reopen the text file after writing the first line

No particular limit on the language. C, C++, C#, Java, Objective-C are all great.

If you know how to do it in Prolog, Haskell, Fortran, Lisp, or Basic then please go right ahead.

88864 次浏览

Windows Batch Files - Version #2

@echo off
echo hello > fileio.txt
echo world  >> fileio.txt
set /P answer=Insert:
echo %answer%  >> fileio.txt
for /f "skip=1 tokens=*" %%A in (fileio.txt) do echo %%A

To explain that last horrible looking for loop, it assumes that there is only hello (newline) world in the file. So it just skips the first line and echos only the second.

Changelog

  • 2 - Opps, must of misread the requirements or they changed on me. Now reads last line from file

C#

string path = "fileio.txt";
File.WriteAllLines(path, new[] { "hello"}); //Will end it with Environment.NewLine
File.AppendAllText(path, "world");


string secondLine = File.ReadLines(path).ElementAt(1);
Console.WriteLine(secondLine);

File.ReadLines(path).ElementAt(1) is .Net 4.0 only, the alternative is File.ReadAllLines(path)[1] which parses the whole file into an array.

For examples of how to do this sort of thing in many languages (61!) try the page on File I/O at Rosetta Code. To be fair, it doesn't appear to answer exactly what you're asking – it's dealing with whole-file I/O – but it's pretty close and covers a wider range than this question is otherwise likely to attract as answers.

Delphi

Delphi, the standard, low-level way (that is, no TStringList and other toys):

program Project1;


{$APPTYPE CONSOLE}


uses
SysUtils;


var
f: Text;
fn: string;
ln: string;


begin


fn := ExtractFilePath(ParamStr(0)) + 'fileio.txt';


// Create a new file
FileMode := fmOpenWrite;
AssignFile(f, fn);
try
Rewrite(f);
Writeln(f, 'hello');
Writeln(f, 'world');
finally
CloseFile(f);
end;


// Read from the file
FileMode := fmOpenRead;
AssignFile(f, fn);
try
Reset(f);
Readln(f, ln);
Readln(f, ln);
Writeln(ln);
finally
CloseFile(f);
end;


end.

Because Delphi is a native Win32 compiler, you can also use the Windows API to handle all I/O operations:

program Project1;


{$APPTYPE CONSOLE}


uses
SysUtils, Windows;


var
f: HFILE;
fn: string;
lns: AnsiString;
fsize, amt, i: cardinal;
AfterLine1: boolean;


const
data = AnsiString('hello'#13#10'world');


begin


fn := ExtractFilePath(ParamStr(0)) + 'fileio.txt';


f := CreateFile(PChar(fn), GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
try
WriteFile(f, data, length(data), amt, nil);
finally
CloseHandle(f);
end;


f := CreateFile(PChar(fn), GENERIC_READ, 0, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
try
fsize := GetFileSize(f, nil);
SetLength(lns, fsize);
ReadFile(f, lns[1], fsize, amt, nil);
for i := 1 to fsize do
case lns[i] of
#10: AfterLine1 := true;
else
if AfterLine1 then
Write(lns[i]);
end;
finally
CloseHandle(f);
end;




end.

And, for completeness, I include the high-level approach, even though I never use it myself:

program Project1;


{$APPTYPE CONSOLE}


uses
SysUtils, Classes;


var
fn: string;


begin


fn := ExtractFilePath(ParamStr(0)) + 'fileio.txt';


with TStringList.Create do
try
Add('hello');
Add('world');
SaveToFile(fn);
finally
Free;
end;


with TStringList.Create do
try
LoadFromFile(fn);
Writeln(Strings[1]);
finally
Free;
end;


end.

Ruby

PATH = 'fileio.txt'
File.open(PATH, 'w') { |file| file.puts "hello" }
File.open(PATH, 'a') { |file| file.puts "world" }
puts line = File.readlines(PATH).last

Haskell

main :: IO ()
main = let filePath = "fileio.txt" in
do writeFile filePath "hello"
appendFile filePath "\nworld"
fileLines <- readFile filePath
let secondLine = (lines fileLines) !! 1
putStrLn secondLine

If you just want to read/write a file:

main :: IO ()
main = readFile "somefile.txt" >>= writeFile "someotherfile.txt"

BASIC

I haven't used BASIC in almost 10 years, but this question gave me a reason to quickly brush up my knowledge. :)

OPEN "fileio.txt" FOR OUTPUT AS 1
PRINT #1, "hello"
PRINT #1, "world"
CLOSE 1


OPEN "fileio.txt" FOR INPUT AS 1
LINE INPUT #1, A$
LINE INPUT #1, A$
CLOSE 1


PRINT A$

Io

f := File with("fileio.txt")
f open
f write("hello")
f close


f openForAppending
f write("\nworld")
f close


f openForReading
secondLine := f readLines at(1)
f close
write(secondLine)

PHP

<?php


$filePath = "fileio.txt";


file_put_contents($filePath, "hello");
file_put_contents($filePath, "\nworld", FILE_APPEND);


$lines = file($filePath);


echo $lines[1];


// closing PHP tags are bad practice in PHP-only files, don't use them

Python 3

with open('fileio.txt', 'w') as f:
f.write('hello')
with open('fileio.txt', 'a') as f:
f.write('\nworld')
with open('fileio.txt') as f:
s = f.readlines()[1]
print(s)

Clarifications

  • readlines() returns a list of all the lines in the file. Therefore, the invokation of readlines() results in reading each and every line of the file. In that particular case it's fine to use readlines() because we have to read the entire file anyway (we want its last line). But if our file contains many lines and we just want to print its nth line, it's unnecessary to read the entire file. Here are some better ways to get the nth line of a file in Python: What substitutes xreadlines() in Python 3?.

  • What is this with statement? The with statement starts a code block where you can use the variable f as a stream object returned from the call to open(). When the with block ends, python calls f.close() automatically. This guarantees the file will be closed when you exit the with block no matter how or when you exit the block (even if you exit it via an unhandled exception). You could call f.close() explicitly, but what if your code raises an exception and you don't get to the f.close() call? That's why the with statement is useful.

  • You don't need to reopen the file before each operation. You can write the whole code inside one with block.

    with open('fileio.txt', 'w+') as f:
    f.write('hello')
    f.write('\nworld')
    s = f.readlines()[1]
    print(s)
    

    I used three with blocks to emphsize the difference between the three operations: write (mode 'w'), append (mode 'a'), read (mode 'r', the default).

JScript (Windows Script Host)

var fileName = "fileio.txt";
var ForReading = 1;
var ForAppending = 8;


var fso = new ActiveXObject("Scripting.FileSystemObject")


// Create a file and write to it
var file = fso.CreateTextFile(fileName, true /* overwrite if exists */);
file.WriteLine("hello");
file.Close();


// Append to the file
file = fso.OpenTextFile(fileName, ForAppending);
file.WriteLine("world");
file.Close();


// Read from the file
file = fso.OpenTextFile(fileName, ForReading);
file.SkipLine();
var str = file.ReadLine();
file.Close();
WScript.Echo(str);

Java

import java.io.*;
import java.util.*;


class Test {
public static void  main(String[] args) throws IOException {
String path = "fileio.txt";
File file = new File(path);


//Creates New File...
try (FileOutputStream fout = new FileOutputStream(file)) {
fout.write("hello\n".getBytes());
}


//Appends To New File...
try (FileOutputStream fout2 = new FileOutputStream(file,true)) {
fout2.write("world\n".getBytes());
}


//Reading the File...
try (BufferedReader fin = new BufferedReader(new FileReader(file))) {
fin.readLine();
System.out.println(fin.readLine());
}
}
}

F#

let path = "fileio.txt"
File.WriteAllText(path, "hello")
File.AppendAllText(path, "\nworld")


let secondLine = File.ReadLines path |> Seq.nth 1
printfn "%s" secondLine

Objective-C

NSFileHandle *fh = [NSFileHandle fileHandleForUpdatingAtPath:@"fileio.txt"];


[[NSFileManager defaultManager] createFileAtPath:@"fileio.txt" contents:nil attributes:nil];


[fh writeData:[@"hello" dataUsingEncoding:NSUTF8StringEncoding]];
[fh writeData:[@"\nworld" dataUsingEncoding:NSUTF8StringEncoding]];


NSArray *linesInFile = [[[NSString stringWithContentsOfFile:@"fileio.txt"
encoding:NSUTF8StringEncoding
error:nil] stringByStandardizingPath]
componentsSeparatedByString:@"\n"];


NSLog(@"%@", [linesInFile objectAtIndex:1]);

Perl

#!/usr/bin/env perl


use 5.10.0;
use utf8;
use strict;
use autodie;
use warnings qw<  FATAL all     >;
use open     qw< :std  :utf8    >;


use English  qw< -no_match_vars >;


# and the last shall be first
END { close(STDOUT) }


my $filename = "fileio.txt";
my($handle, @lines);


$INPUT_RECORD_SEPARATOR = $OUTPUT_RECORD_SEPARATOR = "\n";


open($handle, ">",  $filename);
print $handle "hello";
close($handle);


open($handle, ">>", $filename);
print $handle "world";
close($handle);


open($handle, "<",  $filename);
chomp(@lines = <$handle>);
close($handle);


print STDOUT $lines[1];

Pascal

 Program pascalIO;
Var FName, TFile  : String[15];
UserFile: Text;
Begin
FName := 'fileio.txt';
Assign(UserFile, FName);
Rewrite(UserFile);
Writeln(UserFile,'hello');
Writeln(UserFile,'world');
Close(UserFile);


Assign(UserFile, FName);
Reset(UserFile);
Readln(UserFile,TFile);
Readln(UserFile,TFile);
Writeln( TFile);




Close(UserFile);
End.

VBScript

Adapted From Helen's Answer for JScript.

fileName = "fileio.txt"
Set fso = CreateObject("Scripting.FileSystemObject")


Set file = fso.CreateTextFile(fileName, true)
file.WriteLine("hello")
file.WriteLine("world")
file.Close()


ForReading = 1
Set file = fso.OpenTextFile(fileName, ForReading,false)
file.SkipLine()
WScript.Echo(file.ReadLine())
'Msgbox(file.ReadLine()) 'same as above
file.Close()

ActionScript 3.0

Using Adobe AIR libraries:

import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;


public class fileio
{
public static function doFileIO():void
{
var file:File = File.applicationStorageDirectory.resolvePath("fileio.txt");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeUTFBytes("hello");
stream.writeUTFBytes("\nworld");
stream.close();


stream.open(file, FileMode.READ);
var content:String = stream.readUTFBytes(stream.bytesAvailable);
stream.close();
var input:String = content.split("\n")[1];
trace(input);
}
}

AIR applications cannot write into their directory due to security reasons, so it uses application storage directory.

Boo

import System.IO
path = "fileio.txt"
File.WriteAllText(path, "hello")
File.AppendAllText(path, "\nworld")


secondLine = File.ReadAllLines(path)[1]
print secondLine

JavaScript - node.js

First, lots of nested callbacks.

var fs   = require("fs");
var sys  = require("sys");
var path = "fileio.txt";


fs.writeFile(path, "hello", function (error) {
fs.open(path, "a", 0666, function (error, file) {
fs.write(file, "\nworld", null, "utf-8", function () {
fs.close(file, function (error) {
fs.readFile(path, "utf-8", function (error, data) {
var lines = data.split("\n");
sys.puts(lines[1]);
});
});
});
});
});

A little bit cleaner:

var writeString = function (string, nextAction) {
fs.writeFile(path, string, nextAction);
};


var appendString = function (string, nextAction) {
return function (error, file) {
fs.open(path, "a", 0666, function (error, file) {
fs.write(file, string, null, "utf-8", function () {
fs.close(file, nextAction);
});
});
};
};


var readLine = function (index, nextAction) {
return function (error) {
fs.readFile(path, "utf-8", function (error, data) {
var lines = data.split("\n");
nextAction(lines[index]);
});
};
};


var writeToConsole = function (line) {
sys.puts(line);
};


writeString("hello", appendString("\nworld", readLine(1, writeToConsole)));

FORTRAN

I've been hating FORTRAN recently, so here goes:

      PROGRAM FILEIO
C     WRITES TWO LINES TO A TEXT FILE AND THEN RETRIEVES THE SECOND OF
C     THEM
CHARACTER*5 STRIN
OPEN(UNIT=1, FILE='FILEIO.TXT')
WRITE(1,100) 'HELLO'
WRITE (1,100) 'WORLD'
CLOSE(1)
C
OPEN(UNIT=2, FILE='FILEIO.TXT')
READ(2,100) STRIN
READ(2,100) STRIN
WRITE(*,*) STRIN
100  FORMAT(A5)
STOP
END

Edit by ldigas: I on the other hand rather like it
(sorry for messing with your answer; I didn't feel like starting another Fortran post)

character(10) :: line
open(1,file='fileio.txt',status='replace')
write(1,'("hello"/"world")'); rewind(1);
read(1,'(/a)')line; write(*,'(a)')line
end

(this is a little newer Fortran variant ... only some 15-20 years old ;-)

Ioke

path = "fileio.txt"


FileSystem withOpenFile(path, fn(f,
f println("hello"))
)
FileSystem withOpenFile(path, fn(f,
f println("world"))
)
FileSystem readLines(path) [1] print

ANSI C

#include <stdio.h>
#include <stdlib.h>


int /*ARGSUSED*/
main(char *argv[0], int argc) {
FILE *file;
char buf[128];


if (!(file = fopen("fileio.txt", "w")) {
perror("couldn't open for writing fileio.txt");
exit(1);
}


fprintf(file, "hello");
fclose(file);


if (!(file = fopen("fileio.txt", "a")) {
perror("couldn't opened for appening fileio.txt");
exit(1);
}


fprintf(file, "\nworld");
fclose(file);


if (!(file = fopen("fileio.txt", "r")) {
perror("couldn't open for reading fileio.txt");
exit(1);
}


fgets(buf, sizeof(buf), file);
fgets(buf, sizeof(buf), file);


fclose(file);


puts(buf);


return 0;
}

My mind reading language

(for reference look here)

Done

UniVerse BASIC / UniData UniBASIC

* UFD is the 'User File Directory' in this account
* This may be called &UFD& in UniVerse
OPEN 'UFD' TO F.UFD ELSE
CRT 'CANNOT OPEN UFD'
STOP
END


* Write to file
REC = ''
REC<1> = 'Hello'
REC<2> = 'World'
* When writing to a filesystem, each attribute of a dynamic array is stored
* as a separate line in the file.  When writing to a hashed file (aka, table)
* each attribute is stored separated by a field mark.
WRITE REC TO F.UFD,'fileio.txt'


* Read from file
REC = ''
READ REC FROM F.UFD,'fileio.txt' ELSE
CRT 'CANNOT READ RECORD'
STOP
END
CRT REC<2>

There are other ways to do this, such as using a sequential file (OPENSEQ/READSEQ/WRITESEQ/CLOSESEQ). This is an easy way to do it because it treats the file like any other record.

Shell Script (UNIX)

#!/bin/sh
echo "hello" > fileio.txt
echo "world" >> fileio.txt
LINE=`sed -ne2p fileio.txt`
echo $LINE

Actually the sed -n "2p" part prints the second line, but the question asks for the second line to be stored in a variable and then printed, so... :)

Erlang

Probably not the most idiomatic Erlang, but:

#!/usr/bin/env escript


main(_Args) ->
Filename = "fileio.txt",
ok = file:write_file(Filename, "hello\n", [write]),
ok = file:write_file(Filename, "world\n", [append]),
{ok, File} = file:open(Filename, [read]),
{ok, _FirstLine} = file:read_line(File),
{ok, SecondLine} = file:read_line(File),
ok = file:close(File),
io:format(SecondLine).

Java Me

public static void writeFile(String fileName, String data) {
FileConnection fconn = null;
OutputStream os = null;
try {
String fName = "file:///SDCard/" + fileName;
fconn = (FileConnection) Connector
.open(fName, Connector.READ_WRITE);
if (!fconn.exists()) {
fconn.create();
}
//for append use following line
//os = fconn.openOutputStream(fconn.fileSize());
os = fconn.openOutputStream();
os.write(data.getBytes());
} catch (Exception e) {
System.out.println("Output file error: " + e.getMessage());
} finally {
try {
os.close();
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}


}


}


private static byte[] readFile(String fileName) {
String fName = "file:///SDCard/" + fileName;
byte[] data = null;
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ);
is = fconn.openDataInputStream();
byte b[] = new byte[1024];
int length = is.read(b, 0, 1024);
System.out.println("Content of "+fileName + ": "+ new String(b, 0, length));
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (null != is)
is.close();
if (null != fconn)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return data;
}

Clojure

(use '[clojure.java.io :only (reader)])


(let [file-name "fileio.txt"]
(spit file-name "hello")
(spit file-name "\nworld" :append true)
(println (second (line-seq (reader file-name)))))

Or equivalently, using the threading macro -> (also known as the paren remover):

(use '[clojure.java.io :only (reader)])


(let [file-name "fileio.txt"]
(spit file-name "hello")
(spit file-name "\nworld" :append true)
(-> file-name reader line-seq second println))

C++

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


int main() {
std::fstream file( "fileio.txt",
std::ios::in | std::ios::out | std::ios::trunc  );
file.exceptions( std::ios::failbit );


file << "hello\n" // << std::endl, not \n, if writing includes flushing
<< "world\n";


file.seekg( 0 )
.ignore( std::numeric_limits< std::streamsize >::max(), '\n' );
std::string input_string;
std::getline( file, input_string );


std::cout << input_string << '\n';
}

or somewhat less pedantically,

#include <string>
#include <fstream>
#include <iostream>
using namespace std;


int main() {
fstream file( "fileio.txt", ios::in | ios::out | ios::trunc  );
file.exceptions( ios::failbit );


file << "hello" << endl
<< "world" << endl;


file.seekg( 0 ).ignore( 10000, '\n' );
string input_string;
getline( file, input_string );


cout << input_string << endl;
}

Python 2


Example 1:

with open('fileio.txt', 'a') as f:
f.write('hello')
f.write('\nworld')
with open('fileio.txt') as f:
s = f.readlines()[1]
print s

Example 2 - without context managers:

f = open('fileio.txt', 'a')
f.write('hello')
f.write('\nworld')
f.close()
f = open('fileio.txt')
s = f.readlines()[1]
f.close()
print s

Lua

io.open( 'TestIO.txt', 'w' ):write( 'hello' ):write( '\n', 'world' ):close()
aLine = io.open( 'TestIO.txt', 'r' ):read( '*a' ):match( '%C*%c*(.*)' )
print( aLine )

Tcl

set f [open fileio.txt w+]


puts $f hello
puts $f world


seek $f 0


puts [lindex [split [read $f] \n] 1]


close $f

Groovy

new File("fileio.txt").with {
write  "hello\n"
append "world\n"
println secondLine = readLines()[1]
}

Emacs Lisp

Despite what some people say Emacs is mainly a text editor [1]. So while Emacs Lisp can be used to solve all kinds of problems it is optimized towards the needs of a text editor. Since text editors (obviously) have quite specific needs when it comes to how files are handled this affects what file related functionality Emacs Lisp offers.

Basically this means that Emacs Lisp does not offer functions to open a file as a stream, and read it part by part. Likewise you can't append to a file without loading the whole file first. Instead the file is completely [2] read into a buffer [3], edited and then saved to a file again.

For must tasks you would use Emacs Lisp for this is suitable and if you want to do something that does not involve editing the same functions can be used.

If you want to append to a file over and over again this comes with a huge overhead, but it is possible as demonstrated here. In practice you normally finish making changes to a buffer whether manually or programmatically before writing to a file (just combine the first two s-expressions in the example below).

(with-temp-file "file"
(insert "hello\n"))


(with-temp-file "file"
(insert-file-contents "file")
(goto-char (point-max))
(insert "world\n"))


(with-temp-buffer
(insert-file-contents "file")
(next-line)
(message "%s" (buffer-substring (point) (line-end-position))))

[1] At least I would not go as far as calling it an OS; an alternative UI yes, an OS no.

[2] You can load only parts of a file, but this can only be specified byte-wise.

[3] A buffer is both a datatype in someways similar to a string as well as the "thing you see while editing a file". While editing a buffer is displayed in a window but buffers do not necessarily have to be visible to the user.

Edit: If you want to see the text being inserted into the buffer you obviously have to make it visible, and sleep between actions. Because Emacs normally only redisplays the screen when waiting for user input (and sleeping ain't the same as waiting for input) you also have to force redisplay. This is necessary in this example (use it in place of the second sexp); in practice I never had to use `redisplay' even once - so yes, this is ugly but ...

(with-current-buffer (generate-new-buffer "*demo*")
(pop-to-buffer (current-buffer))
(redisplay)
(sleep-for 1)
(insert-file-contents "file")
(redisplay)
(sleep-for 1)
(goto-char (point-max))
(redisplay)
(sleep-for 1)
(insert "world\n")
(redisplay)
(sleep-for 1)
(write-file "file"))

Progress OpenEdge ABL

DEFINE VARIABLE cString AS CHARACTER NO-UNDO.


OUTPUT TO VALUE("fileio.txt").
PUT UNFORMATTED "hello" SKIP.
OUTPUT CLOSE.


OUTPUT TO VALUE("fileio.txt") APPEND.
PUT UNFORMATTED "world" SKIP.
OUTPUT CLOSE.


INPUT FROM VALUE("fileio.txt").
/* Read each line in to cString; at the end of the loop */
/* the variable will contain the last line of the file. */
REPEAT:
IMPORT UNFORMATTED cString.
END.
INPUT CLOSE.


MESSAGE cString.

Scala:

Using standard library:

val path = "fileio.txt"
val fout = new FileWriter(path)
fout write "hello\n"
fout.close()
val fout0 = new FileWriter(path, true)
fout0 write "world\n"
fout0.close()
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)

Using Josh Suereth's Scala-ARM Library:

val path = "fileio.txt"
for(fout <- managed(new FileWriter(path)))
fout write "hello\n"
for(fout <- managed(new FileWriter(path, true)))
fout write "world\n"
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)


Since many people have used the same file descriptor to write the two strings, I'm also including that way in my answer.

Using standard library:

val path = "fileio.txt"
val fout = new FileWriter(path)
fout write "hello\n"
fout write "world\n"
fout.close()
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)

Using Josh Suereth's Scala-ARM Library:

val path = "fileio.txt"
for(fout <- managed(new FileWriter(path))){
fout write "hello\n"
fout write "world\n"
}
val str = Source.fromFile(path).getLines.toSeq(1)
println(str)

Common Lisp

(defun main ()
(with-open-file (s "fileio.txt" :direction :output :if-exists :supersede)
(format s "hello"))
(with-open-file (s "fileio.txt" :direction :io :if-exists :append)
(format s "~%world")
(file-position s 0)
(loop repeat 2 for line = (read-line s nil nil) finally (print line))))

PowerShell

sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line

x86 Assembler (NASM) on Linux

I haven't touched asm in 7 years, so I had to use google a bit to hack this together, but still, it works ;) I know it's not 100% correct, but hey :D

OK, it doesn't work. sorry bout this. while it does print world in the end, it doesn't print it from the file, but from the ecx which is set on line 27.

section .data
hello db 'hello',10
helloLen equ $-hello
world db 'world',10
worldLen equ $-world
helloFile db 'hello.txt'


section .text
global _start


_start:
mov eax,8
mov ebx,helloFile
mov ecx,00644Q
int 80h


mov ebx,eax


mov eax,4
mov ecx, hello
mov edx, helloLen
int 80h


mov eax,4
mov ecx, world
mov edx, worldLen
int 80h


mov eax,6
int 80h


mov eax,5
mov ebx,helloFile
int 80h


mov eax,3
int 80h


mov eax,4
mov ebx,1
int 80h


xor ebx,ebx
mov eax,1
int 80h

References used: http://www.cin.ufpe.br/~if817/arquivos/asmtut/quickstart.html

http://bluemaster.iu.hio.no/edu/dark/lin-asm/syscalls.html

http://www.digilife.be/quickreferences/QRC/LINUX%20System%20Call%20Quick%20Reference.pdf

MUMPS

FILEIO ;
N F,L1,L2
S F="FILEIO.TXT"
O F:"WNS" U F W "hello" C F
O F:"WAS" U F W !,"world" C F
O F:"RS" U F R L1,L2 C F W L2,!
Q

Visual Basic 6.0

open "fileio.txt" for output as #1
write #1, "hello"
close #1


open "fileio.txt" for append as #1
write #1, "world"
close #1


open "fileio.txt" for input as #1
dim strn as string
input #1, strn
input #1, strn
msgbox(strn)
close #1

AWK

BEGIN {
print "hello" > "fileio.txt"
print "world" > "fileio.txt" # subsequent writes to the same output file append to it
close("fileio.txt")
}


/world/ { print $0 }

To execute the script

$ awk -f script.awk fileio.txt

Python 2 (Alternative solution)

with open('fileio.txt','w') as f:
print>>f,'hello' #write
print>>f,'world'
with open('afile.txt','r') as f:
s = f.readlines()[1] #read
print s

*NIX shell (bash or sh)

#!/bin/bash


echo 'hello' > fileio.txt
echo 'world' >> fileio.txt


myvar=`tail -n 1 fileio.txt`
echo $myvar

PLT Racket

#lang racket
(call-with-output-file "fileio.txt"
#:exists 'truncate
(lambda (out)
(fprintf out "hello\n" )))
(call-with-output-file "fileio.txt"
#:exists 'append
(lambda (out)
(fprintf out "world\n" )))
(call-with-input-file "fileio.txt"
(lambda (in)
(read-line in)
(display (read-line in))))

MATLAB

Using low level routines fopen/fclose/fseek/fscanf/etc

% read a integers from a file...


file = fopen('filename', 'r'); // read only


if (file == -1)
error('file can''t be read');
end


[number, count] = fscanf(file, '%d', 1);


while (count == 1)
fprintf('read %d\n', number);
[number, count] = fscanf(file, '%d', 1);
end


fclose(file);

Using high level routines load/save/textscan/uigetfile/etc

% Load and store a matrix
M = load('sample_file.txt')


save filename M

Python 3

This differs from the other version by using print for all output, and by only opening the file once.

with open('fileio.txt', 'w+') as f:
print('hello', file=f)
pos = f.tell()
print('world', file=f)
f.seek(pos)
s = f.read()
print(s)

K 3

f:`fileio.txt
f 0:/:(*a;a:$`hello`world)
`0:*1_0:f

LOLCODE

The specs are sketchy to say the least, but I did the best I could. Let the downvoting begin! :) I still find it a fun exercise.

HAI
CAN HAS STDIO?
PLZ OPEN FILE "FILEIO.TXT" ITZ "TehFilez"?
AWSUM THX
BTW #There is no standard way to output to files yet...
VISIBLE "Hello" ON TehFilez
BTW #There isn't a standard way to append to files either...
MOAR VISIBLE "World" ON TehFilez
GIMMEH LINES TehLinez OUTTA TehFilez
I HAS A SecondLine ITZ 1 IN MAH TehLinez
VISIBLE SecondLine
O NOES
VISIBLE "OH NOES!!!"
KTHXBYE

Small Basic

path = "c:\fileio.txt"
File.WriteLine(path, 1, "Hello")  'write the first line
File.WriteLine(path, 2, "World")  'write the second line
stuff = File.ReadLine(path, 2)    'read the second line
TextWindow.WriteLine(stuff)

Shell Script

Here's a shell script using just builtin commands, rather than invoking external commands such as sed or tail as previous responses have done.

#!/bin/sh


echo hello > fileio.txt             # Print "hello" to fileio.txt
echo world >> fileio.txt            # Print "world" to fileio.txt, appending
# to what is already there
{ read input; read input; } < fileio.txt
# Read the first two lines of fileio.txt,
# storing the second in $input
echo $input                         # Print the contents of $input

When writing significant shell scripts, it is advisable to use builtins as much as possible, since spawning a separate process can be slow; from a quick test on my machine, the sed solution is about 20 times slower than using read. If you're going to call sed once, as in this case, it doesn't really matter much, as it will execute more quickly than you can notice, but if you're going to execute it hundreds or thousands of times, it can add up.

For those unfamiliar with the syntax, { and } }1 (as opposed to ( and ) which create a subshell; we need to be operating in the current shell environment, so we can use the value of the variable later). We need to group the commands together in order to have them both operate on the same input stream, created by redirecting from fileio.txt; if we simply ran read < fileio.txt; read input < fileio.txt, we would just get the first line, as the file would be closed and re-opened between the two commands. Due to an idiosyncrasy of shell syntax ({ and } are reserved words, as opposed to metacharacters), we need to separate the { and } from the rest of the commands with spaces, and terminate the list of commands with a }0.

The read builtin takes as an argument the names of variables to read into. It consumes a line of input, breaks the input by whitespace (technically, it breaks it according to the contents of $IFS, which defaults to a space character, where a space character means split it on any of space, tab, or newline), assigns each word to the variable names given in order, and assigns the remainder of the line to the last variable. Since we're just supplying one variable, it just puts the whole line in that variable. We reuse the $input variable, since we don't care what's on the first line (if we're using Bash we could just not supply a variable name, but to be portable, you must always supply at least one name).

Note that while you can read lines one at a time, like I do here, a much more common pattern would be to wrap it in a while loop:

while read foo bar baz
do
process $foo $bar $baz
done < input.txt

Go

package main


import (
"os"
"bufio"
"log"
)


func main() {
file, err := os.Open("fileio.txt", os.O_RDWR | os.O_CREATE, 0666)
if err != nil {
log.Exit(err)
}
defer file.Close()


_, err = file.Write([]byte("hello\n"))
if err != nil {
log.Exit(err)
}


_, err = file.Write([]byte("world\n"))
if err != nil {
log.Exit(err)
}


// seek to the beginning
_, err = file.Seek(0,0)
if err != nil {
log.Exit(err)
}


bfile := bufio.NewReader(file)
_, err = bfile.ReadBytes('\n')
if err != nil {
log.Exit(err)
}


line, err := bfile.ReadBytes('\n')
if err != nil {
log.Exit(err)
}


os.Stdout.Write(line)
}

R:

cat("hello\n", file="fileio.txt")
cat("world\n", file="fileio.txt", append=TRUE)
line2 = readLines("fileio.txt", n=2)[2]
cat(line2)

D

module d_io;


import std.stdio;




void main()
{
auto f = File("fileio.txt", "w");
f.writeln("hello");
f.writeln("world");


f.open("fileio.txt", "r");
f.readln;
auto s = f.readln;
writeln(s);
}

MUMPS (not obfuscated)

For historical reasons related to disk space and memory usage ca. 1969, MUMPS allows you to truncate commands to one (or sometimes two) characters, which is why Clayton's example looked so "weird" (although I could read it easily enough). Here's more about what's going on with this MUMPS program.

FileIo ; Define a "label" identifying this piece of code (not a function here).
; MUMPS has only process-specific variable scope, so stack local
; variables with the 'New' command.
New File, Line1, Line2
Set File="FILEIO.TXT"


; MUMPS has a concept of a "currently open" device, which "Read" and "Write"
; commands use.  Identify a device with the Open command and switch to the
; device with the "Use" command.  Get rid of the device with the "Close"
; command.


; Another funny thing here is the "postconditional expression," which in this
; case is "WNS".  In this case we pass arguments to the Open command.  The
; exact meaning is implementation-specific but if I had to guess, these
; arguments have to do with opening the file for writing, using a newline
; character as a delimiter, etc.
Open File:"WNS" Use File Write "hello" Close File
Open File:"WAS" Use File Write !,"world" Close File ; ! = new line


; Here the "Read" command executes twice on the file, reading two lines into
; the variables "Line1" and "Line2".  The Read command is probably aware of the
; line-oriented nature of the file because of the "RS" postconditional.
Open File:"RS" Use File Read Line1,Line2 Close File Write Line2,!
Quit

D with Tango

import tango.text.Util, tango.io.Stdout, tango.io.device.File;


void main()
{
scope file = new File ("fileio.txt", File.ReadWriteCreate);
file.write ("hello\n");
file.write ("world\n");
auto line = splitLines (file.rewind.text())[1];
stdout(line).nl;
}

Condensed version:

void main()
{
with (new File ("fileio.txt", File.ReadWriteCreate))
stdout (lineOf (put("hello\n").put("world\n").rewind.text(), 1)).nl;
}

Factor

For more information (and to download the latest release):

http://www.factorcode.org.

USING: io io.encodings.utf8 io.files ;


"fileio.txt" utf8
[ [ "hello" print ] with-file-writer ]
[ [ "world" print ] with-file-appender ]
[ file-lines last print ] 2tri

Perl 6

use v6;


my $path = 'fileio.txt';


# Open $path for writing.
given open($path, :w) {
.say('hello'); # Print the line "hello\n" to it.
.close; # Close the file.
}


# Open the file for appending.
given open($path, :a) {
.say('world'); # Append the line "world\n" to it.
.close;
}


my $line = lines($path)[1]; # Get the second line. lines returns a lazy iterator.
say $line; # Perl 6 filehandles autochomp, so we use say to add a newline.

EDIT: here's an alternate solution with a small helper function to avoid the need to explicitly close the file.

use v6;


sub with-file($path, *&cb, *%adverbs) {
given open($path, |%adverbs) {
.&cb;
.close;
}
}


my $path = 'fileio.txt';


# Open $path for writing.
with-file $path, :w, {
.say('hello'); # Print the line "hello\n" to it.
};


# Open the file for appending.
with-file $path, :a, {
.say('world'); # Append the line "world\n" to it.
};


my $line = lines($path)[1]; # Get the second line. lines returns a lazy iterator.
say $line; # Perl 6 filehandles autochomp, so we use say to add a newline.

Prolog

% read_line_to_codes is defined in YAP library already.
% Uncomment the next line and remove the makeshift replacement definition to use it.
% use_module(library(readutil)).


readcodes(Stream,[]) :- peek_char(Stream,'\n'),get_char(Stream,'\n');peek_char(Stream,end_of_file).
readcodes(Stream,[First|Rest]) :- get_code(Stream,First),readcodes(Stream,Rest).


read_line_to_codes(Stream,Line) :- readcodes(Stream,Line),!.


:- open('fileio.txt',write,Stream),write(Stream,'hello\n'),close(Stream).
:- open('fileio.txt',append,Stream),write(Stream,'world'),close(Stream).


secondline(L) :- open('fileio.txt',read,Stream),read_line_to_codes(Stream,_),read_line_to_codes(Stream,L),close(Stream).
:- secondline(L),format('~s\n',[L]).

SAS

data;
file 'c:\fileio.txt';
put 'hello' /  'world';


data;
infile 'c:\fileio.txt';
input /;
put _infile_;

C# with Streams

A good C# example was already previously provided, but I felt including how to do file I/O on a line by line basis with streams would be helpful as well.

        string path = @"fileio.txt";


//creating file and writing to it
using (StreamWriter writer = File.CreateText(path))
{
writer.WriteLine("Hello");
}


//appending to existing file
using (StreamWriter writer = File.AppendText(path))
{
writer.WriteLine("World");
}


//reading file
using(StreamReader reader = File.OpenText(path))
{
int lineNum = 0;
string line = null;


while ((line = reader.ReadLine()) != null)//read until eof
{
if (++lineNum == 2)
{
Console.WriteLine(line);
}
}
}

Icon

procedure main(args)
f:=open("fileio.txt","w")
write(f,"hello")
close(f)


f:=open("fileio.txt","a")
write(f,"world")
close(f)


f:=open("fileio.txt","r")
line:=(!f & !f)
# or you can use
# every 1 to 2 do line:=!f
close(f)
write(line)
end

Go

// Disclaimer: I did this mostly because it sounded like a fun quick
// hack, I don't normally use Go at all.
// Using log.Exit like this is probably horrible style.


package main


import (
"bufio"
"fmt"
"log"
"os"
)


func OpenFile(mode int) *os.File {
f, err := os.Open("fileio.txt", mode, 0644)
if err != nil {
log.Exit(err)
}
return f
}


// Create an interface just for fun, since it'll be satisfied
// automatically by bufio's Reader.
type HasReadString interface {
ReadString(b byte) (string, os.Error)
}


func ReadLine(r HasReadString) string {
l, err := r.ReadString('\n')
if err != nil {
log.Exit(err)
}
return l
}


func main() {
f := OpenFile(os.O_CREAT | os.O_TRUNC | os.O_WRONLY)
defer f.Close()
f.WriteString("hello\n")
f.WriteString("world\n")


f = OpenFile(os.O_RDONLY)
defer f.Close()
r := bufio.NewReader(f)
_ = ReadLine(r)
fmt.Print(ReadLine(r))
}

Arc

Original submission:

(w/stdout (outfile "fileio.txt")
prn!hello
prn!world)
(pr:cadr:readfile "fileio.txt")

It was pointed out that this failed to meet the requirements of appending the second line (rather than continuously writing it). waterhouse corrects this and makes other refinements in his version:

(w/outfile f "fileio.txt"
(disp "hello\n" f))
(w/appendfile f "fileio.txt"
(disp "world\n" f))
(pr:cadr:readfile "fileio.txt")

Update: This final revision addresses any concern there might have been about not reading "world" into a variable:

(w/outfile f "fileio.txt"
(disp "hello\n" f))
(w/appendfile f "fileio.txt"
(disp "world\n" f))
(w/infile f "fileio.txt"
(repeat 2 (= l readline.f))
(prn l))

AWK

(without command-line feedback)

BEGIN {
print "hello" > "fileio.txt"
print "world" > "fileio.txt"
for ( i = 0; i < 2; i ++ )
getline < "fileio.txt"
fflush( "fileio.txt" );


print $0
}

CAOS

(the scripting language for the Creatures 3 game engine)

* Open fileio.txt for output (non-append) in global directory
FILE OOPE 0 "fileio.txt" 0
OUTS "hello\n"
OUTS "world\n"
* Close file
FILE OCLO


* Open file for read
FILE IOPE 0 "fileio.txt"
SETS VA00 INNL * read line
SETS VA00 INNL * read line
DBG: OUTS VA00 * print to debug console
FILE ICLO

The original post's running list of links has a couple errors for Arc. Here's the corrected version:

<a href="http://arclanguage.org">Arc</a> -
<a href="http://stackoverflow.com/questions/3538156/file-i-o-in-every-programming-language/3539940#3539940">evanrmurphy</a>

(Sorry to add a whole new Answer for this correction but I have insufficient Reputation to make a comment. Feel free to remove this once it's fixed. Thanks.)

JavaScript - Narwhal on Node

var FS = require("narwhal/fs");
FS.open("fileio.txt", "w")
.print("hello")
.print("world")
.close()


var stream = FS.open("fileio.txt", "r");
stream.next();
print(stream.next());
stream.close();

This is another particular JavaScript embedding.

http://narwhaljs.org

Clojure

Because you want to read line by line, you can't use slurp, so

(use 'clojure.java.io)

And then in traditional lisp style:

(let [f "hello.txt"]
(spit f "hello\n")
(spit f "world\n" :append true)
(print (second (line-seq (reader f)))))

or, bereft of beloved brackets:

(doto "hello.txt"
(spit "hello\n")
(spit "world\n" :append true)
(-> reader line-seq second print ))
Rebol []


write/lines %fileio.txt "hello"
write/lines/append %fileio.txt "world"
print last read/lines %fileio.txt

Python

open('fileio.txt', 'w').write('hello\n')
open('fileio.txt', 'a').write('world\n')
with open('fileio.txt', 'r') as f:
print f.readline() and f.readline(),

ANSI C (POSIX API)

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


#include <stdio.h> /* For error reporting */


#define BUFFER_SIZE 6


int main (int argc, char *argv[])
{
int fd;
const char HELLO[] = "hello\n";
const char WORLD[] = "world\n";


if ((fd = open ("fileio.txt", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)) < 0) {
perror ("open");
return 1;
}


if (write (fd, HELLO, sizeof (HELLO)) < 0) {
perror ("write");
return 1;
}


if (write (fd, WORLD, sizeof (WORLD)) < 0) {
perror ("write(2)");
return 1;
}


/* Rewind file */
lseek (fd, 0, SEEK_SET);


/* Read whole file */
int bytes_read;
do {
char buffer[BUFFER_SIZE];


bytes_read = read (fd, buffer, BUFFER_SIZE);
write (0, buffer, bytes_read);
} while (bytes_read > 0);




if (close (fd) != 0) {
perror ("close");
return 1;
}


return 0;
}

Io

File with("fileio.txt") open write("hello\n") write("world\n") \
rewind readLines second println

Is this the shortest of the solutions?

Brain***k

,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<&
lt;<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<&
lt;-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]

Classic ASP / VBScript

I know this is dying out but, meh!

You can use the optional create parameter in openTextFile to create a non existant text file but I've shown it the long way.

This is untested but should work fine.

<%
Option Explicit


Dim objFso
Dim ourFile
Dim strFilePath
Dim strLine


strFilePath = Map("fileIO.txt")
Set objFso = CreateObject("Scripting.FileSystemObject")


'Create text file, add hello line
Set ourFile = objFso.CreateTextFile(strFilePath)
ourFile.WriteLine("hello")
ourFile.close


'Append world to a newline
Set ourFile = objFso.OpenTextFile(strFilePath, ForWriting)
ourFile.writeline("world")
ourFile.close


'Read lines
Set ourFile = objFso.OpenTextFile(strFilePath, ForReading)
ourFile.skipLine
strLine = ourFile.readLine
ourFile.close


'Print value
response.write(strLine)


'Clean up this shiz
Set ourFile = nothing
Set objFso = nothing
%>

J

f =: 'fileio.txt'
('hello', LF) 1!:2 < f
('world', LF) 1!:3 < f
; 1 { < ;. _2 (1!:1  < f)

The last line reads the file (1!:1 < f), cuts it into lines (< ;. _2), gets the second element (1 {). Then the Monadic ; is used to unbox the element.

Modern Perl

use 5.012;
use warnings;
use autodie;


# 1 & 2 - create and write line to file
open my $new, '>', 'fileio.txt';
say {$new} 'hello';
close $new;


# 3 - open file to append line
open my $append, '>>', 'fileio.txt';
say {$append} 'world';
close $append;


# 4 - read in second line to input string
my $line = do {
open my $read, '<', 'fileio.txt';
<$read>;    # equivalent to: readline $read
<$read>;    # last value expression gets returned from do{}
};


print $line;   # 5 - print input string!

Above is a basic example of using open in Modern Perl (ie. three arg open, lexical filehandles, autodie and say/print best practise).

However it is really unnecessary to pollute the namespace with $new and $append lexical variables (which hold the filehandle). So for points 1-3 I would probably feel happier doing:

{
open my $fh, '>', 'fileio.txt';
say {$fh} 'hello';
}


{
open my $fh, '>>', 'fileio.txt';
say {$fh} 'world';
}

or:

use IO::File;   # core module


IO::File->new( 'fileio.txt', 'w' )->print( "hello\n" );
IO::File->new( 'fileio.txt', 'a' )->print( "world\n" );


Update re: clarification: You don't need to reopen the text file after writing the first line

And no mention whether you need to re-open file for reading back second line thus it can all be done like so:

my $line = do {
open my $fh, '+>', 'fileio.txt';
say {$fh} $_ for qw/hello world/;  # or just: say {$fh} "hello\nworld" :)
seek $fh, 0, 0;                    # rewind to top of file
(<$fh>)[1];                        # no need to be lazy with just 2 recs!
};


print $line;

/I3az/

COBOL

Since nobody else did......

IDENTIFICATION DIVISION.
PROGRAM-ID.  WriteDemo.
AUTHOR.  Mark Mullin.
* Hey, I don't even have a cobol compiler


ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
ORGANIZATION IS LINE SEQUENTIAL.


DATA DIVISION.
FILE SECTION.
FD TestFile.
01 TestData.
02  LineNum        PIC X.
02  LineText       PIC X(72).


PROCEDURE DIVISION.
Begin.
OPEN OUTPUT TestFile
DISPLAY "This language is still around."


PERFORM GetFileDetails
PERFORM UNTIL TestData = SPACES
WRITE TestData
PERFORM GetStudentDetails
END-PERFORM
CLOSE TestFile
STOP RUN.


GetFileDetails.
DISPLAY "Enter - Line number, some text"
DISPLAY "NXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
ACCEPT  TestData.

Coldfusion

Create a new text file called "fileio.txt" Write the first line "hello" to the text file.

 <cffile action="Write" file="fileio.txt" output="hello">

Append the second line "world" to the text file.

<cffile action="Append" file="fileio.txt" output="world">

Read the second line "world" into an input string. Print the input string to the console.

 <cffile action="read" file="fileio.txt" variable="filecontents">
<cfoutput>#ListLast(filecontents,Chr(13) & Chr(10))#</cfoutput>