127
votes

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.

57
  • 9
    The problem with this is that it won't show up in searches for a specific language as it's not, nor can it be, tagged with every language.
    – ChrisF
    Aug 21, 2010 at 17:50
  • 21
    I don't understand why this question is closed. Isn't the purpose of this site to help people find information? If someone knows how to do something (like IO) in C, and wants to learn how to do the same thing in Python, this could help them by allowing them to see both side by side.
    – Slapout
    Aug 21, 2010 at 18:34
  • 18
    I also don't understand why this is closed. It seems like it's just because it doesn't include the words "...in the least amount of characters..." which is pretty silly. Code golf is a fun exercise. But is it really useful to make all the rosetta-stone questions have obfuscated, tiny code in all the answers? Aug 21, 2010 at 18:38
  • 12
    I don't understand how this is fits a Q&A site: at least with code golf, there's a somewhat objective standard by which to vote on answers: the shortest or most clever answer gets the most votes. With this: what is it, how many people like Haskell? Questions like this are like trying to shoehorn every possible type of content into a system that's designed for only one. What's wrong with the rest of the internet for handling this?
    – user113292
    Aug 21, 2010 at 21:40
  • 11
    Why this doesn't work well. No information about the pros and cons of each approach (what languages support only one way?). No discussion of the trade offs and deep issues in each language. Limited scope which implies that the need for a bajiliion separate "in Every Language" questions. And most of all there is no community moderation of the quality of each answer. Why do I say no moderation when people are voting on them? Because there is supposed to be only one answer for each language, and people wont read enough answers to see multiple alternatives in their field. Aug 21, 2010 at 21:44

80 Answers 80

241
votes

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
11
  • 28
    I don't think there's any other language out there to have this property to, literally, make me... lol. Aug 21, 2010 at 23:46
  • 85
    Is it sad that I think LOLCODE is more readable than anything else I've seen?
    – Joel
    Aug 22, 2010 at 1:15
  • 13
    It's intersting how much it feels like a natural language. Aug 22, 2010 at 5:23
  • 19
    Saying that you expect to be downvoted is a guarantee for upvotes on SO because reverse psychology is a reflex action for a programmer. Aug 22, 2010 at 5:42
  • 13
    The PLZ ? / AWSUM THX / O NOES is just terrific. This seems kinda almighty to me.
    – Calvin1602
    Aug 22, 2010 at 10:32
48
votes

Python 3

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

Clarifications

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

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

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

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

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

15
  • 19
    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
    Aug 21, 2010 at 20:42
  • 14
    @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
    Aug 21, 2010 at 21:35
  • 7
    @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. Aug 22, 2010 at 9:36
  • 8
    @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: 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
    Aug 22, 2010 at 10:23
  • 5
    @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
    Aug 22, 2010 at 17:57
43
votes

Brain***k

,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]
3
  • 26
    Did you miss a '-'? ;)
    – Aiden Bell
    Aug 22, 2010 at 19:53
  • 2
    Oh the effort. Just for the record, how much time did it took to write ?
    – Riduidel
    Aug 24, 2010 at 9:03
  • And you can't split that over multiple lines? Best language ever Nov 25, 2011 at 7:49
42
votes

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.
6
  • 2
    This should be voted up no less than 1 million times for pure awesomeness +1 Aug 22, 2010 at 15:24
  • 1
    +1 for "This language is still around." =D Aug 23, 2010 at 7:19
  • 3
    Be careful when trying this at home. Your cobol compiler might not like these modern variable-length lines... Aug 23, 2010 at 9:31
  • Ya, this brings back some rusty ol' memories. I don't think it meets the requirements though...
    – EvilTeach
    Aug 23, 2010 at 19:05
  • I am writing code in AcuCOBOL right now! By the way, where is the "I" part of "I/O?"
    – Buggabill
    Aug 23, 2010 at 19:21
39
votes

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" 
11
  • 7
    Ahh the 'Almighty' Haskell. Thanks for your contribution :) Aug 21, 2010 at 16:53
  • 3
    @Andreas Rejbrand I'm almost sure he forgot a 'be' Aug 21, 2010 at 18:38
  • 4
    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 Aug 22, 2010 at 0:11
  • 4
    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
    Aug 22, 2010 at 7:54
  • 4
    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
    Aug 22, 2010 at 8:00
35
votes

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);
}
2
  • 10
    +1, So much more beautiful and readable than the C++ version! I dream of a day when D completely replaces C and C++. :-) Aug 22, 2010 at 6:31
  • 10
    Nice. Maybe I should learn D some day. Aug 22, 2010 at 20:44
34
votes

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
10
  • 2
    +1 Nice, but to be strict, you don't put the input into a variable before writing it to console. Aug 21, 2010 at 17:10
  • 3
    @lasseespeholt, you're right. I fixed it. Aug 21, 2010 at 19:56
  • 5
    No reason to uppercase varname and say 'PATH'. Just say 'path'.
    – OTZ
    Aug 22, 2010 at 9:18
  • 2
    @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
    Aug 22, 2010 at 10:01
  • 1
    @Thomas Ahle: when using File.open with a block, the file is opened, passed to the block, and then closed automatically.
    – Matchu
    Aug 23, 2010 at 21:25
32
votes

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.

11
  • 1
    its quite short in C#. thanks for contributing Aug 21, 2010 at 16:41
  • 13
    NOTE: File.ReadLines is specific to .NET 4 Aug 22, 2010 at 14:16
  • 5
    What an unpleasant looking syntax C# has
    – Aiden Bell
    Aug 22, 2010 at 19:45
  • 3
    @Aiden Bell: relative to which language?
    – zfedoran
    Aug 24, 2010 at 2:15
  • 2
    @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 dotnetperls.com/file-handling for more realistic examples.
    – Dan Diplo
    Aug 24, 2010 at 9:48
29
votes

ANSI C

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

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

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

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

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

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

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

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

   fclose(file);

   puts(buf);

   return 0;
}
5
  • Nice answer. Thanks for contributing +1 Aug 21, 2010 at 18:35
  • Why do you call fgets() twice? Aug 22, 2010 at 15:35
  • 2
    Because the second line is the one that we want to print to stdout
    – JeremyP
    Aug 22, 2010 at 15:40
  • 1
    #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
    Aug 24, 2010 at 0:38
  • Nice clean coding (lots of decent error checking) in the orignal C post (which blows out the length somewhat).
    – xagyg
    Aug 24, 2010 at 1:59
29
votes

Shell Script (UNIX)

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

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

7
  • 9
    I don't know why, but I love this :) Aug 21, 2010 at 18:52
  • Of course it counts. Nice answer and thanks for contributing +1 Aug 21, 2010 at 18:54
  • Why not sending the standard out to /dev/null?
    – Gumbo
    Aug 21, 2010 at 19:35
  • There's a somewhat simpler, and faster, version, using only shell builtins (as opposed to forking off a separate process to invoke sed), here: stackoverflow.com/questions/3538156/… Aug 22, 2010 at 4:13
  • @Gumbo, Then how would you get the second line? LINE=`foo` captures the output of foo into the variable LINE.
    – strager
    Aug 22, 2010 at 5:27
27
votes

x86 Assembler (NASM) on Linux

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

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

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

section .text
global _start

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

mov ebx,eax

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

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

mov eax,6
int 80h

mov eax,5
mov ebx,helloFile
int 80h

mov eax,3
int 80h

mov eax,4
mov ebx,1
int 80h

xor ebx,ebx
mov eax,1
int 80h

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

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

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

4
  • Are you going to correct it so it works 100%? If not, delete it so a working version can take its place. Aug 22, 2010 at 15:28
  • 4
    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... =) Aug 24, 2010 at 7:42
  • 1
    @Jani: But at least it's somewhat easier to understand.
    – sbi
    Sep 19, 2010 at 7:22
  • Thought it was for DOS at first :)
    – mlvljr
    Oct 7, 2010 at 19:13
21
votes

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)));
9
  • @Ionut: Thanks for your many contributions +1 Aug 21, 2010 at 17:54
  • 4
    @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 nodejs.org Aug 22, 2010 at 0:52
  • 5
    This code is crying out for continuations. I can hear its tears.
    – Matt
    Aug 22, 2010 at 11:07
  • 2
    Isn't it funny the number of lines is almost matching that of the ASM solution downstairs?
    – kizzx2
    Aug 23, 2010 at 17:04
  • 1
    @Matt yes, continuations, or monads would help here as well.
    – Martijn
    Aug 23, 2010 at 23:39
21
votes

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))))
1
  • 1
    for a language called "lisp" there should be a lot more "s" letters involved :)
    – iwasrobbed
    Aug 29, 2010 at 21:57
18
votes

PowerShell

sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line
3
  • 3
    This is nice & clean. Yay powershell.
    – Jay Bazuzi
    Aug 21, 2010 at 21:59
  • 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). Aug 21, 2010 at 22:08
  • 4
    Damn, is there anything shorter??
    – 0fnt
    Aug 23, 2010 at 20:11
18
votes

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
3
  • 3
    Very nice. I learned something (albeit temporarily). Aug 22, 2010 at 4:53
  • Thanks for your contribution Brian. Aug 22, 2010 at 8:58
  • Totally sick! In a good way :-) Aug 22, 2010 at 20:41
18
votes

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))
6
  • 1
    WTF, for the last 50 years almost nobody said Lisp/Scheme rocks! Aug 21, 2010 at 23:41
  • 11
    Wait, spit is really the name of the write-to-file function?
    – Sam Stokes
    Aug 22, 2010 at 8:03
  • 4
    Clojure definitely does not rock! Aug 22, 2010 at 15:31
  • 1
    @[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
    Aug 23, 2010 at 19:09
  • 4
    @kirk.burleson Rocks more than Java, certainly. :)
    – Rayne
    Aug 23, 2010 at 19:09
17
votes

F#

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

let secondLine = File.ReadLines path |> Seq.nth 1
printfn "%s" secondLine
1
  • 1
    F#. Nice. Thanks for your contribution. Aug 21, 2010 at 17:32
16
votes

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$
5
  • It's amazing you could still do this after 10 years!. Well done and thanks for your contribution. Aug 21, 2010 at 16:56
  • I of course didn't do it off the top of my head: took a few minutes to look up some stuff.
    – casablanca
    Aug 21, 2010 at 17:00
  • Yeah of course. Still well done. Aug 21, 2010 at 17:25
  • Don't you need line numbers in the most classic version of BASIC ???
    – Yuji
    Aug 21, 2010 at 18:10
  • @Yuji: In the "most classic version", yes, but I don't think any version since the early 90s has required them.
    – casablanca
    Aug 21, 2010 at 19:38
16
votes

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]);
13
  • 17
    I've never liked Objective-C. The syntax just seems so foreign when coming from a language like Java. Aug 21, 2010 at 17:43
  • 5
    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 Aug 21, 2010 at 19:44
  • 7
    And i thought the c++ syntax already looked the worst.
    – Toad
    Aug 21, 2010 at 20:58
  • 6
    Objective-C only looks bad because the Stackoverflow syntax highlighter doesn't get coloured correctly. Aug 22, 2010 at 3:44
  • 4
    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
    Aug 24, 2010 at 11:20
16
votes

Perl

#!/usr/bin/env perl

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

use English  qw< -no_match_vars >;

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

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

$INPUT_RECORD_SEPARATOR = $OUTPUT_RECORD_SEPARATOR = "\n";

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

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

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

print STDOUT $lines[1];
19
  • 15
    what about lexical filehandles, 3 argument open?
    – MkV
    Aug 21, 2010 at 20:59
  • 6
    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
    Aug 23, 2010 at 4:01
  • 4
    Same goes for two argument open: You should never use it on Stack Overflow, and probably not in practice.
    – rpkelly
    Aug 24, 2010 at 1:46
  • 2
    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. Aug 24, 2010 at 8:11
  • 2
    "Even unary open has its uses",it has its uses, yes, but I felt abused the day I worked out how that works, and will go "Surely there is another way" every time I see somebody who thinks they need it. perl -we 'for (q{ps aux |}){ open _; print <_>; }' Nov 21, 2010 at 19:59
15
votes

R:

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

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
5
  • Thats great. Thanks for the contribution. Aug 21, 2010 at 17:45
  • 20
    Alternatively, you could take the C implementation and add dollar signs. Aug 22, 2010 at 5:17
  • @strager I have no idea. There are people who don't know it's optinal and that it's actually better without it. Aug 22, 2010 at 13:41
  • 6
    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
    Aug 24, 2010 at 2:40
  • Reference for no ?>: framework.zend.com/manual/en/…
    – cdmckay
    Aug 24, 2010 at 23:03
15
votes

Java

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

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

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

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

    //Reading the File...
    try (BufferedReader fin = new BufferedReader(new FileReader(file))) {
      fin.readLine();
      System.out.println(fin.readLine());
    }       
  }
}
23
  • 36
    @Brock: These days Java is not slow. Just verbose, but not slow. Please don't make such comments; hurts us JVM people. :'| Aug 21, 2010 at 17:37
  • 9
    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. Aug 21, 2010 at 18:00
  • 4
    @Missing Faktor: And so? Aug 21, 2010 at 18:58
  • 19
    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) Aug 21, 2010 at 21:25
  • 11
    "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. Aug 22, 2010 at 0:36
14
votes

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;
}
10
  • 1
    Great! Thanks for contributing +1 Aug 21, 2010 at 19:30
  • 14
    I forgot how ugly c++'s syntax can be.
    – Toad
    Aug 21, 2010 at 20:55
  • 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. Aug 21, 2010 at 21:45
  • 8
    @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.) Aug 22, 2010 at 14:02
  • 2
    Now I know why Linus says C++ is ugly. (no offense)
    – kizzx2
    Aug 23, 2010 at 17:03
13
votes

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)
}
6
  • 23
    This language should be renamed "type"
    – Aiden Bell
    Aug 22, 2010 at 19:52
  • Is that os.O_RDWR | os.O_CREATE, 0666 junk even necessary for basic file I/O in Go?
    – Joey Adams
    Aug 23, 2010 at 20:59
  • 1
    Or maybe it should be renamed "Stop"
    – xagyg
    Aug 24, 2010 at 1:56
  • 16
    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.
    Aug 24, 2010 at 9:02
  • 5
    Wow... Go seems so much Fail with this example Aug 24, 2010 at 17:24
12
votes

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).
0
12
votes

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"))
1
  • 1
    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
    Aug 22, 2010 at 8:17
11
votes

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

3
  • neat. thanks for your contribution. Aug 21, 2010 at 16:28
  • I understand step 4) as reading from the created file.
    – devio
    Aug 21, 2010 at 19:09
  • @devio - The requirements must have changed or I just misread them... Anyway I'll see if such a solution even exists
    – TheLQ
    Aug 21, 2010 at 19:21
11
votes

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)
7
  • I think this would look nicer with flush() instead of close()... no re-instantiating of the FileWriter.
    – Radtoo
    Aug 22, 2010 at 7:39
  • 2
    @Radtoo: Had to show the append operation. That's why I did it this way. Aug 22, 2010 at 7:53
  • @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.) Aug 23, 2010 at 7:41
  • @Missing Faktor, getLines().toList() should be getLines().toSeq which is lazy? Aug 24, 2010 at 5:54
  • @Missing Faktor, also you can drop the parenthesis. This is not Java. Aug 25, 2010 at 8:08
11
votes

Groovy

new File("fileio.txt").with { 
    write  "hello\n"
    append "world\n"   
    println secondLine = readLines()[1]
}
2
  • 3
    You are cheating on the "world\n" part. It's not appending, it is just writing to the same file descriptor.
    – OTZ
    Aug 22, 2010 at 9:10
  • The 3rd clarification in the original post states "You don't need to reopen the text file after writing the first line" Aug 22, 2010 at 21:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.