views:

56678

answers:

80

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 =)

Votes:

Vote up answers which have good naming conventions, and are easy to understand.

+11  A: 

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
TheLQ
neat. thanks for your contribution.
Brock Woolf
I understand step 4) as *reading* from the created file.
devio
@devio - The requirements must have changed or I just misread them... Anyway I'll see if such a solution even exists
TheLQ
+35  A: 

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.

lasseespeholt
its quite short in C#. thanks for contributing
Brock Woolf
@abatishchev The edit was not valid, you added two newlines so the output would be `""`. I will get `NewLine` incorporated if you like that better.
lasseespeholt
@lasseespeholt: Thanks, you're right. I just want to mention that C#/.NET has this feature. P.S. what for info about lines?
abatishchev
@abatishchev "P.S. what for info about lines?", I'm not sure what you are asking about.
lasseespeholt
@abatishchev I have included `.WriteAllLines` now for the first write instead and actually reduced the code a little. `.WriteAllLines` leaves a `Environment.NewLine` linebreak at the end.
lasseespeholt
Why downvote? please comment
lasseespeholt
@lasseespeholt: "4-5 lines (;)" - what for is this?
abatishchev
NOTE: File.ReadLines is specific to .NET 4
kirk.burleson
What an unpleasant looking syntax C# has
Aiden Bell
@Aiden Bell: relative to which language?
Arriu
@Aiden Bell - This answer is trying to be succinct over readable. There are a lot "nice" ways of achieving the same thing in C#. See http://dotnetperls.com/file-handling for more realistic examples.
Dan Diplo
@Aiden Bell: LOL
abatishchev
@Dan Diplo +1 nice link, but I see it does not have .Net 4.0 methods like `File.ReadLines` which should replace the `StreamReader.ReadLine` example.
lasseespeholt
+8  A: 

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.

Donal Fellows
Yes. But that doesn't answer the question I am asking. "this sort of thing" isn't the same file IO that i am asking to do.
Brock Woolf
Are you sure that you do not mean 61, and not 61! ?
Andreas Rejbrand
Just for the record - 61! = 507580213877224798800856812176625227226004528988036003099405939480985600000000000000
belisarius
@Andreas: Hah! (which is has got to be in at least base 18 to be meaningful. (18*18*17+18*10+17)! has 18955 digits though, so I'm not about to paste it in a comment. :-))
Donal Fellows
@Belisarius: Don't you mean - 61! = - 50758…
Potatoswatter
@belisarius Thank you so much for shifting the block of zeros one to the right - makes the whole number suddenly perfectly readable.
Dave
@Dave That was just to be sure that the 14 fives are there ... :D
belisarius
+9  A: 

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.
Andreas Rejbrand
Delphi reminds me of prolog for some reason :) thanks for your contribution
Brock Woolf
Well, in Delphi 2010, there are at least two other ways of reading and writing to files, but I cannot write a book here...
Andreas Rejbrand
Why a downvote?
Andreas Rejbrand
I think you pretty much scared everyone away from Delphi.
kirk.burleson
@Andreas: for starting of with `AssignFile`. The seventies are over.
Henk Holterman
@Henk Holterman: I don't get it. This is the standard way of working with files in Delphi (at the lowest level, not using Windows API)... It is not overly complicated in any way...
Andreas Rejbrand
No, this not 'standard'. It is the (very) old way to do it. There is a Pascal answer here, there it is appropriate.
Henk Holterman
@Henk Holterman: I always use this method...
Andreas Rejbrand
Then maybe it's time to move on to the 21st century. Use a Stream, not File/Text
Henk Holterman
@Henk Holterman: Why abandon a perfectly working system? The low-level approach is fast (as fast as it gets), very easy to use, and completely unlimited since it gives you full control. Maybe I should add that I read/write binary files more often than text files, and when it comes to binary files, there are not as many alternatives to the low-level approach. Hence it feels natural for me always to use it, even for text-files. But still: why abandon a method that works perfectly? I know that some people are afraid of low-level, manual, stuff, but I am not.
Andreas Rejbrand
@Henk Holterman: "Then maybe it's time to move on to the 21st century" newer/shiner doesn't mean "better".
SigTerm
@Andreas: "Why abandon a perfectly working system?" Assembler is perfectly working, too. However, _ease of maintainance_ turned out to become a very important feature of software a few decades ago.
sbi
@sbi: The old way is very easy to maintain; I cannot see why any new way would be easier.
Andreas Rejbrand
@Andreas: Then why aren't you doing assembler?? Honestly, I know little of Delphi and my Pascal is pretty rotten, but from what I can see I'd prefer the last piece of code to be dropped into my lap when you're leaving the company.
sbi
+32  A: 

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
Wayne Conrad
short and sweet. thanks for your contribution.
Brock Woolf
+1 Nice, but to be strict, you don't put the input into a variable before writing it to console.
lasseespeholt
@lasseespeholt, you're right. I fixed it.
Wayne Conrad
No reason to uppercase varname and say 'PATH'. Just say 'path'.
OTZ
@otz It's a constant. He could have called it 'Path' though, a constant in Ruby just has to start with an uppercase letter.
Sirupsen
To CONSTANT (or Constant), or not to constant, that is the question...
Wayne Conrad
No need for closing?
Thomas Ahle
@Thomas Ahle: when using `File.open` with a block, the file is opened, passed to the block, and then closed automatically.
Matchu
I would get rid of the PATH constant to make it even shorter. It wouldn't be harder to read.
felipec
Ahh Ruby. No wonder Ruby programmers are all so superior!
Kyle
Due to the new (1.9.x) string encoding, I personally have gotten into the habit of opening everything (including text) as binary. Also, for performance, I tend to read files explicitly to the filesize. So:File.open(PATH, 'wb') {|f| f.puts "hello"}; File.open(PATH, 'ab') {|f| f.puts "world"}; puts File.open(FILE) {|f| f.read(f.stat.size)}
todb
+37  A: 

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" 
Ionuț G. Stan
Ahh the 'Almighty' Haskell. Thanks for your contribution :)
Brock Woolf
How can a side effect possible in a functional language??? People exclaim "Monad!", but I never managed to understand ...
Yuji
Yuji: "How can a side effect possibly *WHAT* in a functional language"?
Andreas Rejbrand
@Andreas Rejbrand I'm almost sure he forgot a 'be'
klez
Ugh... please forgive a poor non-native English speaker:p
Yuji
There are a number of other approaches to basic I/O in Haskell that become useful / important in Haskell once you're doing certain types of apps. The text and bytestring packages on cabal/hackage let you deal with various encodings, and various iteratee style packages such as iteratee and enumerate represent a "best known abstraction" for doing incremental io. Also important are parsing libs like parsec and the incremental bytestring only attoparsec lib.Haskellers have taken a very thorough approach to exploring io design choices. Nonviable examples include lazy io and continuations
Carter Tazio Schonwald
Yuji: basically, by cheating. Haskell is a pure functional language, *except* for anything of type `IO a`, which has special compiler support for side effects. (Purity is preserved elsewhere because *anything* which performs or observes a side effect is of type `IO a`, so the type system ensures the rest of your program stays pure.)
Sam Stokes
It so happens that `IO` is a monad, but that's not why it's allowed to do side effects. Being a monad is what lets you write that imperative-looking syntax: it also makes sure (also with special language support) the side effects happen in a sensible order, so you don't read from the file before you write to it, etc.
Sam Stokes
If only I were smart enough to understand Haskell :/
Brock Woolf
Can I be pedantic and share some itches about this piece of code? :-) I would push the first let into the do-block (just like the second let, for symmetry), and the second let doesn't need any parentheses.
Martijn
@Martijn, sure :) I had the same thought about the first let, but I decided to go with it outside the do block as a means to show it's not dependent on those side-effects. Your symmetry reason sounds better at this time though. As for the parens, well, I's still a newbie in Haskell. Thanks for the feedback.
Ionuț G. Stan
+14  A: 

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$
casablanca
It's amazing you could still do this after 10 years!. Well done and thanks for your contribution.
Brock Woolf
I of course didn't do it off the top of my head: took a few minutes to look up some stuff.
casablanca
Yeah of course. Still well done.
Brock Woolf
Don't you need line numbers in the most classic version of BASIC ???
Yuji
@Yuji: In the "most classic version", yes, but I don't think any version since the early 90s has required them.
casablanca
+5  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)
Ionuț G. Stan
The poetic irony!
trinithis
Lo. First language I've never heard of. Thanks for the contribution.
Brock Woolf
Actually, it's Io, with uppercase i, not Lo. :)
Ionuț G. Stan
@Brock Woolf, You were born with the knowledge of language names like C++, Java, and Haskell?
strager
@strager: Correct.
Brock Woolf
Bad naming for a programming language. can't distinguish if it's 'L' or 'I'.
OTZ
@otz, Can't distinguish between ♯ and #.
strager
@strager Actually I *can*. Plus, unlike I and l, ♯ is a multibyte character, which nobody bothers to use under normal conditions.
OTZ
@otz Точно? ("Really?" in Russian. Yes, I do use multibyte characters in normal conditions.)
whitequark
I've put `Io` inside <code> elements. Monospace fonts should make the name clear now.
Ionuț G. Stan
Not very idiomatic, that's for sure.
Justin Poliey
@Justin, feel free to edit the entry.
Ionuț G. Stan
+13  A: 

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
Ionuț G. Stan
Thats great. Thanks for the contribution.
Brock Woolf
Alternatively, you could take the C implementation and add dollar signs.
Kendall Hopkins
What's with that `?>`? ;P
strager
@strager I have no idea. There are people who don't know it's optinal and that it's actually better without it.
Ionuț G. Stan
Just in case anybody is curious, the reason he left off the closing tag is because if you include it, and leave any trailing white space, you risk getting a 'headers already sent' error.
Bill H
Reference for no `?>`: http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html
cdmckay
+47  A: 

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: http://stackoverflow.com/questions/3541274/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).

snakile
Python. Neat, elegant, concise. Thanks for contributing.
Brock Woolf
Is `with` a construct to help you dispose of the resource? Or what is that for?
notJim
@notJim: The with statement starts a code block where you can use the variable f (or any other variable) as a stream object returned from the call to open(). When the with block ends, python calls f.close() automatically. This garantees 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 can 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.
snakile
I really don't think anyone should ever write `readlines()[1]` in example code. In this case you may know the file only has two lines, but someone else blithely assuming it's a good solution might try it on a million-line file and get a rather nasty surprise.
Porculus
@Porculus with readlines() we don't go through all the lines in the file. This is python 3. readlines() returns an iterator (not a list). Therefore only the first two lines of the file will be read. This is similar to xreadlines() in python 2 (which doesn't exist in python 3).
snakile
@notJim, short answer: yes.
Ionuț G. Stan
@snakile: could you please cite something in support of *`readlines()` returns an iterator (not a list)* Just a note: you typically cannot index an iterator.
SilentGhost
OTZ
@SilentGhost I'm quoting "Dive into Python 3": "The readlines() method now returns an iterator, so it is just as efficient as xreadlines() was in Python 2". Search this statement in: http://diveintopython3.org/porting-code-to-python-3-with-2to3.html. Second, in python 3 you can index an iterator. Type range(10)[4] in the shell (range() also returns an iterator in Python 3 in contrary to python 2 where range() returns a list). Note that range(N)[i] is done in O(i), not O(1) and not O(N).
snakile
Also works in Python 2.6, btw.
Jesse Aldridge
@snakile: Your comments are wrong on several levels. First, readlines returns a list in Python 3 (test it and see). So the code given will read the entire file. Second, iterators can not be indexed in Python 2 or 3. The `range` object has special support for indexing, which is done in O(1).
interjay
...you can always edit an answer if you have a small correction to make. Just sayin.
colithium
@snakile: as interjay says, and [official docs confirm](http://docs.python.org/py3k/library/io.html#io.IOBase.readlines), `readlines` returns a list, not an iterator. `range` is not just an iterator, it's a range object.
SilentGhost
@Porculus, @SilentGhost, @interjay, @colithium, thanks for your remarks. I was wrong about readlines() (well, I just followed "dive into python"'s wrongness).I added clarifications to my answer. Sorry for being wrong on the internet.
snakile
"You don't need to reopen the text file after writing the first line"
stepancheg
Marking a correct answer is hard. I'm choosing Python because: it's available to all platforms; The code is brief and concise; no matter what system you run, the Python implementation should be fairly easy to get running. Oh and I like Python, even if I suck at it. also marking my own answer correct would be a conflict of interest as much as I would like to choose Objective-C.
Brock Woolf
+5  A: 

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);
Helen
VBScript Version isn't all so different...
st0le
@st0le: Yes; I just like JScript better.
Helen
Thanks for your contribution.
Brock Woolf
+17  A: 

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...
    FileOutputStream fout = new FileOutputStream(file);
    fout.write("hello\n".getBytes());
    fout.close();

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

    //Reading the File...
    BufferedReader fin = new BufferedReader(new FileReader(file));
    String firstLine = fin.readLine();
    String secondLine = fin.readLine();
    fin.close();

    System.out.println(secondLine);          
  }
}
st0le
@Brock: These days Java is not slow. Just verbose, but not slow. Please don't make such comments; hurts us JVM people. :'|
missingfaktor
Thanks for contributing +1
Brock Woolf
Whoever said Java is slow is either a blind Java hater or lives under a rock. Java can be as fast as, if not faster than C, with platform independence to boot.
NullUserException
Jerry Coffin
@Missing Faktor you have my support :)
Mite Mitreski
Don't take it seriously guys. Java isn't slow it was only a joke. Relax :)
Brock Woolf
@Jerry: Comparing with the languages that compile to native code doesn't prove anything. If you want real comparison, compare with C#, F#, Smalltalk etc.
missingfaktor
@Missing Faktor: why is a comparison to Smalltalk or F# "real", while a comparison to C or C++ "doesn't prove anything"?
Jerry Coffin
@Missing Faktor: And so?
Jerry Coffin
@Jerry: So nothing. I didn't say Java is the fastest language on planet. I just said it's fast, which means it's pretty fast for the purposes it is used.
missingfaktor
@Jerry: As Paul Biggar says [here](http://stackoverflow.com/questions/1517868/performance-of-java-1-6-vs-c/1517874#1517874), "Which (alioth stats) should be taken with a grain of salt. Firstly, you can write the program as you like. I know haskell does well, but the code is not idiomatic, so the cheap tricks you'd never use come out. Secondly, it only uses tiny programs. Few interesting Java and C++ programs are less than 10000 lines of code. Many are greater than 1 million LOC.". And as a matter of fact, it is well accepted that Java CAN be as fast as (or sometimes even faster) than C or C++.
missingfaktor
@Jerry: No further comments from me on this topic.
missingfaktor
@Missing Faktor: No benchmark is 100% accurate. In reality, however, they're likely to show Java in an unrealistically *favorable* light. First, most use many iterations of small loops -- minimizing the time spent JIT compiling, but maximizing its effect. Second, most run only for short periods of time, minimizing (often eliminating) time spent garbage collecting. IMO, "1 million LOC" is mostly a cheap ploy to make it a) unreasonable for anybody to ask you to back up the claim, and b) unlikely they'll be able to show objective proof you're wrong.
Jerry Coffin
@Jerry: because java and C#/F# are compiled to some form of intermediate language, not directly to native. C and C++ have a leg up by being directly compiled to machine code.
RCIX
execution speed is the most retarded form of pissing contests programmers have. It is always about choosing the right tool for the job, choosing a random metric like execution speed and assigning heaps of importance to it is just silly, especially since execution speed isn't horribly important for the vast majority of tasks, as long as it is fast enough (which java is for almost everything)
Matt Briggs
@Missing Faktor - pace Paul Biggar - any performance comparison between different programming languages should be taken with a grain of salt, for all the reasons listed on the benchmarks game website - http://shootout.alioth.debian.org/flawed-benchmarks.php
igouy
@Missing Faktor - "And as a matter of fact, it is well accepted that..." - Please show that as a matter of fact "Java CAN be as fast as (or sometimes even faster) than C or C++". Do you mean we can always find a way to make a program to run more slowly? :-)
igouy
@Matt Briggs - "execution speed isn't horribly important for the vast majority of tasks, as long as it is fast enough" - Make your mind up: if it isn't important then it doesn't matter if it's "fast enough", if it has to be "fast enough" then it is important.
igouy
"hardwiring is faster than machine code", "machine code is faster than asm", "asm is faster than C", "C is faster than Java", "blah blah blah"... Do you even have one clue how much indirection is already between machine code and CPU? microcode, predictive optimizer, instruction/data caches, decoder, etc, not to mention nondeterminism caused by dynamic allocation in C/asm. Java and other safe languages are just one more small step of indirection, it's no big deal. You can either stay in your primitive form forever or evolve with us.
Longpoke
Java IO is slow as hell and consumes incredibly much memory.
Dave
Reading about databases is the best way to improve the performance of your application. Ok, this statement isn't always true but it is very often true.
TTT
A shorter version, if you interest (new FileWriter("fileio.txt"){{write("hello\n");}}).close(); (new FileWriter("fileio.txt", true){{write("world\n");}}).close(); (new LineNumberReader(new FileReader("fileio.txt")){{ setLineNumber(2); System.out.println(readLine()); }}).close();
Dennis Cheung
+17  A: 

F#

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

let secondLine = File.ReadLines path |> Seq.nth 1
printfn "%s" secondLine
lasseespeholt
F#. Nice. Thanks for your contribution.
Brock Woolf
+13  A: 

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]);
Brock Woolf
I've never liked Objective-C. The syntax just seems so foreign when coming from a language like Java.
Faisal Abid
@Faisal: Obj-C is very close to Java: in any case they are imperative, object-oriented languages. You'll be appalled by Prolog etc, which has a totally different mindset.
Yuji
The secret to Objective-C is that Xcode does all the code completion for you. You don't have to remember the long method names. They certainly make your code much more readable though
Brock Woolf
And i thought the c++ syntax already looked the worst.
Toad
Objective-C only looks bad because the Stackoverflow syntax highlighter doesn't get coloured correctly.
Brock Woolf
You can just use `+[NSFileHandle fileHandleForUpdatingAtPath:]` so you can read and write from the same handle
Dave DeLong
@Dave Delong: Thanks for your help it looks much neater now.
Brock Woolf
Wow, looks like such a terrible language to write in. Calling it "C" is a disgrace.
Gautam
Like Mac, it's really hard to make people understand advantages of Objective-C.
Eonil
@Gautam,@Eonil: Thanks for the Obj-C bashing. It only shows your ignorance and limited skill as a programmer when it comes to looking at something different to the one language you know.
Brock Woolf
I can't believe this is so far down the list! Also the Java guys commenting that Objective-C is ugly, did you see how many lines it took to write the same file? I used to be a Java enthusiast, but I think Objective-C has crept it's way into my heart.
Kyle
Of course, plain C would be perfectly fine for the Objective-C compiler, too. This example seems to intentionally do everything as "Objective-C-ish" as possible... Would ObjC programmers actually do that, for the trivial task at hand in the example here?
tml
@tml: Yes we do. Why use 50 lines of C when 8 lines of Obj-C do a much better job.
Brock Woolf
+15  A: 

Perl

#!/usr/bin/perl

  use strict;

  # opens file for writing; overwrites contents if file already exists
  open(my $out, ">", "fileio.txt") or die "Cannot open fileio.txt";
  print $out "hello\n";
  close($out);

  # opens file for writing in append mode
  open($out, ">>", "fileio.txt") or die "Cannot open fileio.txt";
  print $out "world\n";
  close($out);

  # opens file for input
  open(my $in, "<", "fileio.txt") or die "Cannot open fileio.txt";

  # "slurps" file into an array using newline as separator.
  my @lines = <$in>;
  close($in);

  print $lines[1];

You can specify I/O layers that change how input and output are processed. For example:

open(my $in, "<:crlf", "file.txt") or die "Cannot open file";

Assumes the input file uses CF/LF (DOS-style) line endings. You can also use it when writing to files:

open(my $out, ">:utf8", "file.txt") or die "Cannot open file";

This outputs in UTF-8.

Perl also lets you open a file in read/write mode. You can write to a file normally, but you will have to read it with seek:

open(my $in, ">+", "file.txt") or die "Cannot open file"; # +> will also work
Vivin Paliath
Thanks very much for this contribution. Very neat +1
Brock Woolf
o.O perl i can read... ;)
RCIX
what about lexical filehandles, 3 argument open?
MkV
@MkV on second thought, for completeness, I added that info. Thanks for reminding me :)
Vivin Paliath
Non-lexical filehandles should never be used on Stack Overflow. There is rarely a need for them in practice, and beginners should not ever be shown that that they even exist.
Ether
Same goes for two argument open: You should never use it on Stack Overflow, and probably not in practice.
rpkelly
I use 3-arg open and lexical filehandles so much I practically consider it a syntax error when I see it. And so it should be. /me ponders writing a module to make it so.
Kent Fredric
Thanks for the comments, guys. I was not aware of that best-practice. Will change it now.
Vivin Paliath
+5  A: 

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.
Mite Mitreski
I had no compiler to check but i think its is ok
Mite Mitreski
Looks good. Thanks for the contribution.
Brock Woolf
I have't used it in over 6 years bit rusty :)
Mite Mitreski
I guess TFile should be a string, too. And you don't need Txt.
devio
Beautiful :) I don't know why, but I'm fond of this syntax. Perhaps because it reminds me of high school :)
Danita
@devio corrected
Mite Mitreski
+2  A: 

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()
st0le
Thanks for your contribution.
Brock Woolf
+8  A: 

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.

alxx
Thanks for your contribution.
Brock Woolf
+3  A: 

Boo

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

secondLine = File.ReadAllLines(path)[1]
print secondLine
st0le
Seems just like C#. ;)
st0le
Thanks for contributing +1
Brock Woolf
@st0le Yeah, a little smaller, though. In a real-world app `ReadLines` may be better than the array `ReadAllLines` so its not making the hole file (with ex 10k lines) into an array when only the second line is needed.
lasseespeholt
+16  A: 

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)));
Ionuț G. Stan
@Ionut: Thanks for your many contributions +1
Brock Woolf
Is }); a js smiley?
Hans Passant
@Hans, haha. Nice one :)
Ionuț G. Stan
Since when can js write data to your file system???
Dave
@Dave, it's not the JS found in the browsers. I mean, syntactically and semantically, it's the same JS, just the standard library is different. I used the stdlib of the `node.js` platform. See http://nodejs.org/
Ionuț G. Stan
This code is crying out for continuations. I can hear its tears.
Matt
@Hans Passant - Looks like a texan oil merchant (the type with bullhorns on his 10 gallon hat), giving you the snake-oil wink.
Aiden Bell
JS is the new Lisp
kizzx2
Isn't it funny the number of lines is almost matching that of the ASM solution downstairs?
kizzx2
@Matt yes, continuations, or monads would help here as well.
Martijn
+5  A: 
JasonFruit
Thanks for the Fortran contribution +1
Brock Woolf
@Idigas, I've been working with FORTRAN 77; Fortran 90 added a lot of nice things to the language, but most of the source code I've been looking at is . . . dusty.
JasonFruit
@JasonFruit - Quite understandable. We've all been there. But, unless you are working on a legacy system (maintaining) and are constrained by an old compiler, there is no need to continue using only f77 features.
ldigas
+4  A: 

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
Ionuț G. Stan
thanks for the contribution
Brock Woolf
+31  A: 

ANSI C

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

int main(void)
{
   FILE *file;
   char buf[128];

   file = fopen("fileio.txt", "w");
   if (!file)
   {
      fprintf(stderr, "Couldn't open file.\n");
      exit(1);
   }

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

   file = fopen("fileio.txt", "a");
   if (!file)
   {
      fprintf(stderr, "Couldn't open file.\n");
      exit(1);
   }

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

   file = fopen("fileio.txt", "r");
   if (!file)
   {
      fprintf(stderr, "Couldn't open file.\n");
      exit(1);
   }

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

   fclose(file);

   puts(buf);

   return 0;
}
Maister
Nice answer. Thanks for contributing +1
Brock Woolf
Why do you call fgets() twice?
kirk.burleson
Because the second line is the one that we want to print to stdout
JeremyP
#include <stdio.h>int main(void){ FILE *file; char buf[128]; file = fopen("fileio.txt", "w"); if (!file) goto error; fputs("hello\n", file); fflush(file); fputs("world\n", file); fclose(file); file = fopen("fileio.txt", "r"); if (!file) goto error; fgets(buf, sizeof(buf), file); /* skip 'hello' */ fgets(buf, sizeof(buf), file); /* get 'word' */ fclose(file); fputs(buf, stdout); return 0;error: fputs("Couldn't open file\n", stderr); return 1;}
felipec
Nice clean coding (lots of decent error checking) in the orignal C post (which blows out the length somewhat).
xagyg
A: 

My mind reading language

(for reference look here)

Done
klez
P.S. I know it will be downvoted :)
klez
@klez: You are correct, as a good mind reader should be. :)
bcat
@bcat, I'm not the mind reader, it's the programming language :) It's strange it didn't feel it would be downvoted and crash the entire SO site!
klez
That's not a very good mind-reading language if it can't automatically tell when you're done.
dan04
Where can I gets this language - it rocks!
David Hoerster
Isn't there a badge for getting so many downvotes? XD
klez
This doesn't compile with me :(
ldigas
I keep getting a "Error reading `Mind`. `Mind` does not exist.` error...
st0le
+2  A: 

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.

Dave
+30  A: 

Shell Script (UNIX)

#!/bin/sh
echo "hello" > fileio.txt
echo "world" >> fileio.txt
LINE=`sed -n "2p" 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... :)

robertbasic
I don't know why, but I love this :)
klez
Of course it counts. Nice answer and thanks for contributing +1
Brock Woolf
Why not sending the standard out to /dev/null?
Gumbo
There's a somewhat simpler, and faster, version, using only shell builtins (as opposed to forking off a separate process to invoke `sed`), here: http://stackoverflow.com/questions/3538156/fileio-in-every-programming-language/3539272#3539272
Brian Campbell
@Gumbo, Then how would you get the second line? `LINE=\`foo\`` captures the output of `foo` into the variable `LINE`.
strager
+11  A: 

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).
clofresh
thanks for contributing
Brock Woolf
Erlang rocks...
T.K.
"ok!" is all I have to say.
Zolomon
+1  A: 

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;
    }
Vivart
+15  A: 

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))
abhin4v
+1 Clojure rocks!
Helper Method
@abhin4v: Thanks for your contribution
Brock Woolf
WTF, for the last 50 years *almost* nobody said Lisp/Scheme rocks!
Ionuț G. Stan
Wait, `spit` is really the name of the write-to-file function?
Sam Stokes
Clojure definitely does not rock!
kirk.burleson
@[Sam Stokes] There is a function in core called slurp that reads an entire file into a string and returns it. spit does the exact opposite. What's the issue? There are other functions, like line-seq, that do similar things in different ways.
Rayne
@kirk.burleson Rocks more than Java, certainly. :)
Rayne
clojure is a nasty scheme
xagyg
Needs more parentheses
raspi
+14  A: 

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;
}
Potatoswatter
Great! Thanks for contributing +1
Brock Woolf
I forgot how ugly c++'s syntax can be.
Toad
This *is* atrocious compared to what most C++ code looks like. The main problem is a lack of appropriate constants defined in the standard library, though, not syntax. It blows me away that I need to include `<limits>` just to tell `ignore` there *isn't* a limit to the line size.
Potatoswatter
This is what happens when you put I/O handling in a library instead of the language. The language was already full. Most C++ programmers would argue that is the very reason C++ is still around.
Hans Passant
@Hans: Would you like to clarify that? Personally, I think I/O _belongs_ in a library rather than in the language, and all the languages I program in do it that way (C, C++, Java, Python, etc.)
Chinmay Kanchi
Now I know why Linus says C++ is ugly. (no offense)
kizzx2
+6  A: 

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
Corey Goldberg
thanks for contributing +1
Brock Woolf
Does this fully follow the rules? This appends both `hello` and `world` to the file. The rules said that `hello` must be written to the file and `world` should be appended. Unless this is accepted... (I'm not too sure of what the OP meant).
vlad003
Instead of `f.readlines()[1]` which will read the entire file, you could use `f.next(); s = f.next()` which will read only the first two lines. Or use itertools.islice(f, 1,2)[0]
Dave Kirby
@Vlad: Yes you are correct that is what I meant.
Brock Woolf
+7  A: 

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 )
Petite Abeille
Thanks for contributing.
Brock Woolf
+6  A: 

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
Tcl
thanks for contributing
Brock Woolf
This is not code golf. Code should be better written for clarity instead of trying to show off terseness.
slebetman
Note also that the line `puts [lindex [read $f] 1]` is a hack and breaks if the first line contains more than one word (or an unbalanced brace or anything that makes the file as a whole an invalid list)
slebetman
Pedantry: it's Tcl, not TCL.
David N. Welton
+11  A: 

Groovy

new File("fileio.txt").with { 

    write  "hello\n"
    append "world\n"   

    println secondLine = readLines()[1]
}
Wayne Keenan
thanks for contributing.
Brock Woolf
You are cheating on the "world\n" part. It's not appending, it is just writing to the same file descriptor.
OTZ
The 3rd clarification in the original post states "You don't need to reopen the text file after writing the first line"
Wayne Keenan
+12  A: 

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"))
tarsius
thanks for contributing
Brock Woolf
nice thanks. Is it possible to enhance this so I actually see a 'ghost' opening the file and typing to it, like a macro of some sort?
zedoo
@zedoo here you go
tarsius
+2  A: 

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.
AbeVoelker
Thanks for contributing.
Brock Woolf
+10  A: 

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)
missingfaktor
I think this would look nicer with flush() instead of close()... no re-instantiating of the FileWriter.
Radtoo
@Radtoo: Had to show the append operation. That's why I did it this way.
missingfaktor
@Radtoo: After looking at other answers in this thread, I finally decided to include that way in my answer. Check it. (I haven't removed the original code though.)
missingfaktor
@Missing Faktor, `getLines().toList()` should be `getLines().toSeq` which is lazy?
Elazar Leibovich
@Elazar: Good suggestion. Thanks. :)
missingfaktor
@Missing Faktor, also you can drop the parenthesis. This is not Java.
Elazar Leibovich
Two downvotes? Care to explain, downvoters?
missingfaktor
+21  A: 

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))))
twopoint718
for a language called "lisp" there should be a lot more "s" letters involved :)
iWasRobbed
+18  A: 

PowerShell

sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line
lasseespeholt
Jay Bazuzi
I agree with your logic about quoting. The reason I removed them was that I realized that this script is actually in the top for being compact so I wanted it to me even smaller - but we let it be clear :). And the use of `gc` instead of `cat` makes sense :-) `get-alias` gave me `cat` first (I'm not using PowerShell much).
lasseespeholt
Damn, is there anything shorter??
+23  A: 

x86 Assembler (NASM)

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

robertbasic
thanks for contributing +1
Brock Woolf
Are you going to correct it so it works 100%? If not, delete it so a working version can take its place.
kirk.burleson
Takes me back :)
cdm9002
What's kind of funny is that the example in C, which is supposed to be a higher level language, is about as long as this one... =)
Jani Hartikainen
@Jani: But at least it's somewhat easier to understand.
sbi
Thought it was for DOS at first :)
mlvljr
+2  A: 

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
Clayton
The hell? (15 chars)
TheLQ
Apparently those are abbreviated keywords. http://en.wikipedia.org/wiki/MUMPS and http://en.wikipedia.org/wiki/MUMPS_Language_Syntax might help decode it… this is supposed to be instructional, not codegolf.
Potatoswatter
Never mind, see other answer http://stackoverflow.com/questions/3538156/fileio-in-every-programming-language/3539510#3539510
Potatoswatter
I'm sure it makes sense to MUMPS developers...
kirk.burleson
+6  A: 

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
qwerty1793
thanks for writing this ... brings lots of memories :)
Ahmed Kotb
+2  A: 

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
Helper Method
Posted a version that doesn't require the file as an argument: http://stackoverflow.com/questions/3538156/fileio-in-every-programming-language/3540279#3540279
Potatoswatter
+3  A: 

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
Chinmay Kanchi
Edited because the print statement already adds new lines so the `\n` only add extra blank lines in. But anyways, nice use of the print statement. Never knew it could do that. I'm assuming it's appending the text to the specified object?
vlad003
Yes, I only discovered this recently, but `print>>f` redirects output to any open file-like object. Thanks for the edit.
Chinmay Kanchi
+5  A: 

*NIX shell (bash or sh)

#!/bin/bash

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

myvar=`tail -n 1 fileio.txt`
echo $myvar
Chinmay Kanchi
+1 For using tail :-)
Helper Method
I agree. Much more straightforward than the `sed` answer.
dan04
+4  A: 

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))))
Jason Baker
+3  A: 

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
Pmod
+2  A: 

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)
dan04
+4  A: 

K 3

f:`fileio.txt
f 0:/:(*a;a:$`hello`world)
`0:*1_0:f
Did you make this up?
kirk.burleson
Whether you consider this a proper append or not depends on your interpretation of the problem. The same goes for the read. The solution given is what most people would take for proper form.For the read there is also the "fields" version of dyadic 0:.If you allow that the output file does not conform to expectation, then 5: dyadic can be used with two "appends." The monadic 1: read function can be used to read the file, and indexing to the second element is the same as reading only the second line, since the file is mmapped into memory. These variations are less natural.
http://en.wikipedia.org/wiki/K_%28programming_language%29
Chris Dennett
+220  A: 

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
Danita
I thought of trying LOLCODE, but it seems that file I/O isn't defined by the specs :)
Chinmay Kanchi
I don't think there's any other language out there to have this property to, literally, make me... lol.
Ionuț G. Stan
Is it sad that I think LOLCODE is more readable than anything else I've seen?
Joel
It's intersting how much it feels like a natural language.
abhin4v
Saying that you expect to be downvoted is a guarantee for upvotes on SO because reverse psychology is a reflex action for a programmer.
Brock Woolf
The PLZ ? / AWSUM THX / O NOES is just terrific. This seems kinda almighty to me.
Calvin1602
I actually imagined some guy or some kid reading this code out loud while typing it in. "Ok, I gonna write this program ..."Opens up the editor: "Hi, can I has a standard IO"Here he's bored as he starts all his programs with these lines. "Mmmm ... Please, open file ... mmmm ... 'The Files'..."He hits enter here and says a little bit lauder: "Awesome, thanks!"and so on...
Andrew
@Joel: Be careful with saying that! A manager might overhear you and mandate its use to replace their old Cobol apps, and then we'll all be stuck with it for decades.
Donal Fellows
I would have expected LOLCODE to use one-based indexing, since that is more natural to small kittens.
Andreas Rejbrand
@Andreas I actually gave that a second thought but I stuck with zero-based indexing because other small kitten friendly languages like LOGO seem to use it as well :)
Danita
+2  A: 

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)
David Hoerster
This doesn't satisfy the requirements. You're supposed to write "hello" and "world" on two separate lines, then read just the second line back in again, then print what you just read in from the second line.
Brian Campbell
Updated <filler>
David Hoerster
+16  A: 

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 } execute a list of commands in the current shell environment (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 ;.

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
Brian Campbell
Very nice. I learned something (albeit temporarily).
Potatoswatter
Thanks for your contribution Brian.
Brock Woolf
Totally sick! In a good way :-)
Helper Method
+11  A: 

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)
}
eclark
This language should be renamed "type"
Aiden Bell
Haha! Good one, @Aiden! :D
missingfaktor
Is that `os.O_RDWR | os.O_CREATE, 0666` junk even necessary for basic file I/O in Go?
Joey Adams
Or maybe it should be renamed "Stop"
xagyg
It's rather amazing that given 30 years of evolution and language design, they've still managed to invent a new language that's as hard to write error-checking code in as C. Even Java's less verbose!
DK
@DK - That's because it seems primates designed Go, after misunderstanding C.
Aiden Bell
Wow... Go seems so much Fail with this example
Alessandro Stamatto
Go: there is no `try`
CyberShadow
+14  A: 

R:

cat("hello\n", file="fileio.txt")
cat("world\n", file="fileio.txt", append=TRUE)
line2 = readLines("fileio.txt", n=2)[2]
cat(line2)
David F
+31  A: 

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);
}
Bernard
+1, So much more beautiful and readable than the C++ version! I dream of a day when D completely replaces C and C++. :-)
missingfaktor
Nice. Maybe I should learn D some day.
Helper Method
+6  A: 

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
Sean Woods
@Sean: Thanks for explaining this code. Just to clarify those arguments to Open: "WNS" means to open the file for writing (W), Create a new file (N), and make it a stream-oriented file (S). The following Open uses "WAS", with A meaning Append. "RS" later on means to open the file for Reading, in Stream mode.
Clayton
+6  A: 

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;    
}
doh
+8  A: 

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
mrjbq7
+1, was waiting for someone to do it in `factor`.... :)
st0le
+7  A: 

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.
ekiru
Perl actually makes me sad. No language ever needs a keyword 'given'. What next, 'beholdeth' or 'insomuchas'
Aiden Bell
@Aiden: `given` in Perl 6 is similar to Clojure's `doto` macro. It lets you avoid repeating the name of the object on which to invoke methods.
missingfaktor
Is the .close necessary, or does the file handle fall out of scope, closing the file, at the end of the "given" block?
jplindstrom
@jplindstrom: The .close is necessary. Perl 6 doesn't mandate reference counting GC, so there's no real way to guarantee timely destruction of objects, so even if the file-handle's DESTROY closed the file, it wouldn't be closed until the next GC run after it falls out of scope. Ideally, there could be a with-file function such that "with-file $path, :w, { .say('hello') }", and the file-handle would automatically be closed after executing the block. I've edited my original answer to add an example of how that would look.
ekiru
+6  A: 

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]).
artificialidiot
+1  A: 

SAS

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

data;
infile 'c:\fileio.txt'; 
input /; 
put _infile_;
tedc
+6  A: 

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);
                }
            }
        }
Judicium
Is there a reason why you not `break` within `if (++lineNum == 2)`?
lasseespeholt
Simply because I wanted the loop to exit when the end of file was reached for sake of demonstration.
Judicium
Is there a reason you're doing this... StreamWriter writer = File.CreateText(path); writer.WriteLine("Hello"); writer.Close();Instead of the more idiomatic this... using(StreamWriter writer = File.CreateText(path)) writer.WriteLine("Hello");The using statement should be used to manage disposable resources rather than manually disposing which can lead to leaks.
Ramon Leon
I forgot to do so in throwing this snippet together, but that would indeed make this a better example. Thank you for bringing it to my attention.
Judicium
This example could be cut to a third of its length by omitting unnecessary curly braces.
sbi
I could make it shorter yes by nixing the braces, but my personal preference is to keep them. To me it's a bit easier to read, it looks consistent with the blocks of code with more than one line in them, and if I want to add more code later I don't need to re-add the braces...or worse yet forget to add them...so it's less logic error-prone.
Judicium
@Judicium: (Unless you properly @address comment replies, they won't show up in the responses tab of those your reply to. I only found this accidentally.) Now that you cut the code by applying `using` it doesn't matter all that much anymore. But I hate it when I have to scroll through code snippets on SO.
sbi
+2  A: 

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
artificialidiot
+1  A: 

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))
}
durin42
+3  A: 

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))
evanrmurphy
That's very nice, but aren't we supposed to be appending the second line rather than doing a continuous write?
John Lawrence Aspden
@John fixed :)Related question: Is it a requirement that "world" be read into a variable before it's printed?
evanrmurphy
+4  A: 

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
}
Potatoswatter
Don't you need to close "fileio.txt" after printing to it? Otherwise it doesn't seem to produce any output.
Helper Method
@Helper: It works for me. I thought your program needed to `close` to reset the I/O position in the file, so its contents would be subsequently read. Typically closing files at application termination is unnecessary.
Potatoswatter
Which implementation of awk are you using? At least with gawk (GNU awk) it doesn't seem to work. This may be implementation-specific.
Helper Method
@Helper: I'm on OS X. If I query `awk --version` it replies `awk version 20070501`. Really, it just trashes the data unless you add `close` at the end? What about `flush`? That is a very unusual way for any program to work. The OS and standard library are pretty diligent about flushing things on shutdown. Does the return status indicate abnormal exit?
Potatoswatter
@Potato Okay, flushing also works, which is probably a lot cleaner than closing the file.
Helper Method
+3  A: 

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
bdonlan
A: 

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

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

(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.)

evanrmurphy
+4  A: 

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

Kris Kowal
+4  A: 

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 ))
John Lawrence Aspden
Where is clojure.core/slurp-lines?
John Lawrence Aspden
+10  A: 
Rebol []

write/lines %fileio.txt "hello"
write/lines/append %fileio.txt "world"
print last read/lines %fileio.txt
Graham Chiu
+5  A: 

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(),
OTZ
+5  A: 

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;
}
el.pescado
C99 has fgets and fputs.
felipec
`fgets` and `fputs` are part of C standard library, not POSIX. There is already example using stdio.
el.pescado
+6  A: 

Io

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

Is this the shortest of the solutions?

Steve Dekorte
-1, You are using the same file descriptor to write the two strings and read the second string back. As per the specification, you should be using three separate file descriptors instead.
missingfaktor
@Miss: it only says *not* to reopen the file between "hello" and "world".
Potatoswatter
@Pota: This wasn't the code I commented to. See the edit hisory of the answer.
missingfaktor
+42  A: 

Brain***k

,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]
Svisstack
Hah, I love it!
Tom Gullen
I just want to say f*k.
kirk.burleson
Did you miss a '-'? ;)
Aiden Bell
Oh the effort. Just for the record, how much time did it took to write ?
Riduidel
+2  A: 

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
%>
Tom Gullen
+4  A: 

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.

Bertrand Marron
+7  A: 

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/

draegtun
+34  A: 

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.
Mark Mullin
This should be voted up no less than 1 million times for pure awesomeness +1
Brock Woolf
+1 for "This language is still around." =D
missingfaktor
Be careful when trying this at home. Your cobol compiler might not like these modern variable-length lines...
Stephan Eggermont
Ya, this brings back some rusty ol' memories. I don't think it meets the requirements though...
EvilTeach
I am writing code in AcuCOBOL right now! By the way, where is the "I" part of "I/O?"
Buggabill
I part is in GetFileDetails - just threw it together from memory, haven't written a COBOL app (minus a few sprocs for DB2) in several decades
Mark Mullin
+3  A: 

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>
Brian Bolton