127

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.

animuson
  • 53,861
  • 28
  • 137
  • 147
Brock Woolf
  • 46,656
  • 50
  • 121
  • 144
  • 2
    Can we assume that fileio.txt don't already exist or do we have to turncate a pre-existing fileio.txt file? – slebetman Aug 21 '10 at 16:29
  • assume that the text file doesn't exist – Brock Woolf Aug 21 '10 at 16:31
  • 4
    At least IMO, it would be (drastically) more useful if the example had to deal with EOF. I don't remember seeing a question that I could point this as answering, but *constantly* see questions where they want to read a whole file and deal with EOF incorrectly. – Jerry Coffin Aug 21 '10 at 17:13
  • 2
    Does the file need to be closed and re-opened before appending, or is it OK to just write two lines one after another? – Helen Aug 21 '10 at 17:25
  • I guess the question arises because you mentioned "appending" and there is usually a special append mode when opening a file. – casablanca Aug 21 '10 at 17:39
  • Most answers you go and complain about the language in some way. Voting to close based on that. It's annoying. – Amy B Aug 21 '10 at 17:40
  • @Coronatus: Sorry about that. I've removed all such comments. – Brock Woolf Aug 21 '10 at 17:43
  • 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 '10 at 17:50
  • @ChrisF: But this applies to code-golf "questions" as well (and they are, generally, allowed). – Andreas Rejbrand Aug 21 '10 at 17:53
  • 1
    @ChrisF: If this is a popular question people will find it if they search for "FileIO" which I've done before. I just figured this would be an interesting question for many people. I am also intrigued for how other languages compare to Objective-C and C++ which are what I am most familiar with. – Brock Woolf Aug 21 '10 at 18:00
  • 2
    To add to @ChrisF's comment, this question isn't really language-agnostic. Language-agnostic means that the language is irrelevant, but for this question, the language does matter; it's just that every language is alowed. – Pops Aug 21 '10 at 18:05
  • 3
    @Andreas: [Code-golf has a special remit](http://meta.stackexchange.com/questions/20912/so-weekly-code-golf), and it is not based on any claim to provide a encyclopedia on "How to do it". Further, even if people find this "question" the examples supplied are too limited to be of much help without finding a separate discussion or going and reading the documentation...so, what's the point, again? – dmckee --- ex-moderator kitten Aug 21 '10 at 18:07
  • 4
    I found it clear, precise, complete, non-rhetorical, and easily answered. But that's just me, and I'm not a . . . what was that word again, Matt? – JasonFruit Aug 21 '10 at 18:24
  • 3
    This is a great question that generated lots of good answers. Vote to reopen. – Brock Woolf Aug 21 '10 at 18:24
  • 4
    @Matt there are, indeed, a lot of other bad questions. That does not make this a good one. And abusive language is always out of line. – dmckee --- ex-moderator kitten Aug 21 '10 at 18:30
  • 1
    @dmckee: There is no abusive language. I don't know what you're talking about. – Brock Woolf Aug 21 '10 at 18:32
  • 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 '10 at 18:34
  • 2
    @Slapout: Thats right. Seeing the implementations side by side is the value of the question and why I asked it in the first place. – Brock Woolf Aug 21 '10 at 18:37
  • 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? – spencer nelson Aug 21 '10 at 18:38
  • 1
    @Andreas - "code golf" questions are a special case. This isn't trying to do file I/O in the least number of bytes (or whatever). Ah I see @dmckee has already made this point. – ChrisF Aug 21 '10 at 18:45
  • Lol, thease edit collisions are funny – TheLQ Aug 21 '10 at 19:50
  • I'd like to make a request for x86 Assembly. All common 3 versions, one from no OS, one from Windows, and one from Linux :) – Earlz Aug 21 '10 at 19:59
  • 1
    @dmckee: I wasn't trying to be abuse, just a little bit abrasive ;-) It comes from a bit of annoyance with the over zealous moderation here. There is nothing wrong with fun questions, so long as the site doesn't get overrun with them. This is community wiki and better then most, so if you close this you are just being a jerk. – Matt Briggs Aug 21 '10 at 20:05
  • 3
    @JasonFruit: SO is primarily for questions that actually have answers. Give me a snippet in every language imaginable doesn't really fit that. That being said, "soft" questions are typically allowed here, for a period of time, and only if they are community wiki. Origionally, the author was pretty much bashing all the answers, that alone is close worthy, but that was removed. What I was saying is that this falls into that category, and if you still voting to close, you are being a jerk. I am sorry if you were offended, that isn't really offensive language where I am from. – Matt Briggs Aug 21 '10 at 20:15
  • Anyone going to do Google Go? :) – Chris Dennett Aug 21 '10 at 20:42
  • 1
    @Chris Dennett: Probably not (for a while). Closed again. – Andreas Rejbrand Aug 21 '10 at 20:46
  • Why have the answers not been voted into alphabetical order ;) – Paul Ruane Aug 21 '10 at 20:52
  • 8
    Folks, the only reason this stayed open as long as it did is because it was asked at the weekend. If this was asked anytime Monday to Friday it wouldn't have lasted 5 minutes. This isn't what SO is for. I encourage you all to read the FAQ, I'm sure for some it won't be for the first time either. – Binary Worrier Aug 21 '10 at 20:57
  • Can we edit the question to make it seem more like a question? – Chris Dennett Aug 21 '10 at 20:57
  • 2
    @Binary Perhaps you should read the FAQ. Any of the code-golf **like** questions do not fall under the rule "Avoid asking questions that are subjective, argumentative, or require extended discussion". This isn't subjective (can use any language), argumentative (not a "Which one is best?" question), or requires extended discussion (see argumentative). Going strictly by the FAQ (which you are), this is a perfectly legal question – TheLQ Aug 21 '10 at 21:09
  • 1
    @Chris Dennett: Now someone can write a piece of Go code! – Andreas Rejbrand Aug 21 '10 at 21:13
  • 1
    It is a good question, lot of good answers. – fastcodejava Aug 21 '10 at 21:23
  • 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? –  Aug 21 '10 at 21:40
  • 4
    >> So I figure here we can create a community resource << How do you know the code snippets actually do what was asked? – igouy Aug 21 '10 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. – dmckee --- ex-moderator kitten Aug 21 '10 at 21:44
  • 4
    The endless editing smack of attention boosting. We don't need an update for every answer that is posted. – dmckee --- ex-moderator kitten Aug 21 '10 at 21:46
  • 1
    Dmckee: dude your banging your head off a brick wall, this guy thinks this is a great idea ... therefore, it's a great idea. It doesn't matter how much sense you make, he doesn't want to hear it. – Binary Worrier Aug 21 '10 at 22:17
  • 1
    @Matt Briggs: I just now voted to close it because of you. Have a nice day. – JUST MY correct OPINION Aug 22 '10 at 03:05
  • @dmckee: This is but a SINGLE question. If it bothers you, there are other places where you can shake your fist. It seems that people believe this question is valid and constructive. – Brock Woolf Aug 22 '10 at 07:03
  • 1
    Do a Google search for "fileio". This question is the 8th answer on the front page. Seems searchable to me. – Brock Woolf Aug 22 '10 at 07:08
  • Related: [Factorial algorithms in different languages](http://stackoverflow.com/questions/23930/factorial-algorithms-in-different-languages) – Helen Aug 22 '10 at 08:47
  • 8
    The answers, along with each contributor, already exists in the text **under** the question. Duplicating this info is redundant. If you keep editing the question, it is eventually going to be locked. – Marc Gravell Aug 22 '10 at 09:05
  • @Helen: If you start relating questions like that, you will have to relate every Rosetta Stone question with every other Rosetta Stone question. i.e. 8646 associations ;) [ http://stackoverflow.com/questions/tagged/rosetta-stone ] – missingfaktor Aug 22 '10 at 09:08
  • 2
    How about this: WHOEVER GETS TO WRITE THIS IN BRAINF**K WINS! – OTZ Aug 22 '10 at 10:30
  • @dmckee --- finally, a good reason not to do this question. That's an excellent point. – JasonFruit Aug 22 '10 at 12:04
  • @Matt Briggs --- I think you have me confused with someone else. I mentioned you with immoderate glee. – JasonFruit Aug 22 '10 at 12:05
  • @dmckee: What you are asking is not possible. You couldn't possibly come up with a question that would fulfil all of those requirements you stated. You are being extremely over zealous about this. Let it go. – Brock Woolf Aug 22 '10 at 12:12
  • 2
    @Marc I really liked seeing the list of languages linking to each answer at the bottom of the question. I think it provides a nice "table of contents" for the answers. – Ben McCormack Aug 22 '10 at 15:36
  • 1
    I've deleted my x86 Assembler version cause didn't manage to get a 100% working version out. Hopefully someone will show up with an example to see where I did wrong :) learning++ – robertbasic Aug 22 '10 at 17:09
  • 8
    Admittedly, I usually like language-agnostic challenge questions (like code golf), but I'm starting to doubt their appropriateness on SO. And this question illustrates why. It highlights a rather glaring problem: the voting mechanism ends up meaning absolutely nothing. On a normal question that asks how to do something **for a specific language** the voting helps to move the best approach to the top. But for questions like this, people seem to vote more for what's amusing or what's their favorite language, so it's just a popularity contest. Vetting of an answers correctness is hindered. – gnovice Aug 22 '10 at 18:07
  • @gnovice, I agree entirely +1 on your comment and a vote to close from me. – Rob Aug 22 '10 at 18:24
  • 1
    @gnovice - well put. Someone lock it?! – Aiden Bell Aug 22 '10 at 20:02
  • Lol, this question was reopened AGAIN. I'm creating a question on meta for thease kinds of questions – TheLQ Aug 23 '10 at 00:07
  • 1
    Can anyone explain how this question causes harm to Stackoverflow.com? There are many more people who want this open. I fail to see the problem here. – Brock Woolf Aug 23 '10 at 00:07
  • Every time this gets reopened, a kitten cries. @Brock Woolf: I think a few of us explained very clearly why we think this post should remain closed. –  Aug 23 '10 at 00:25
  • Everytime this gets closed, a baby cries. @Mark Trapp: I have found these answers very insightful. No doubt others have as well. – Brock Woolf Aug 23 '10 at 00:33
  • @Brock **Discussion has moved to meta** http://meta.stackexchange.com/questions/61906/community-wiki-questions-and-the-subjective-close – TheLQ Aug 23 '10 at 01:03

80 Answers80

241

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
Community
  • 1
  • 1
Danita
  • 2,464
  • 4
  • 23
  • 29
  • I thought of trying LOLCODE, but it seems that file I/O isn't defined by the specs :) – Chinmay Kanchi Aug 21 '10 at 22:41
  • 28
    I don't think there's any other language out there to have this property to, literally, make me... lol. – Ionuț G. Stan Aug 21 '10 at 23:46
  • 85
    Is it sad that I think LOLCODE is more readable than anything else I've seen? – Joel Aug 22 '10 at 01:15
  • 13
    It's intersting how much it feels like a natural language. – Abhinav Sarkar Aug 22 '10 at 05: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. – Brock Woolf Aug 22 '10 at 05:42
  • 13
    The PLZ ? / AWSUM THX / O NOES is just terrific. This seems kinda almighty to me. – Calvin1602 Aug 22 '10 at 10:32
  • 2
    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... – Andrei Андрей Листочкин Aug 23 '10 at 14:35
  • 2
    @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 Aug 23 '10 at 20:11
  • 3
    I would have expected LOLCODE to use one-based indexing, since that is more natural to small kittens. – Andreas Rejbrand Aug 24 '10 at 10:30
  • @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 Aug 24 '10 at 12:55
  • This one should have been the accepted answer – TheIronKnuckle Nov 25 '11 at 07:48
48

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

Community
  • 1
  • 1
snakile
  • 52,936
  • 62
  • 169
  • 241
  • 3
    Python. Neat, elegant, concise. Thanks for contributing. – Brock Woolf Aug 21 '10 at 17:31
  • 2
    Is `with` a construct to help you dispose of the resource? Or what is that for? – davidtbernal Aug 21 '10 at 19:24
  • 2
    @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 Aug 21 '10 at 19:37
  • 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 '10 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 '10 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. – SilentGhost Aug 22 '10 at 09:36
  • I've written a more elegant version of this answer. Please vote it up for Python's sake: http://stackoverflow.com/questions/3538156?tab=votes&page=3#tab-top – OTZ Aug 22 '10 at 10:12
  • 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: 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 Aug 22 '10 at 10:23
  • Also works in Python 2.6, btw. – Jesse Aldridge Aug 22 '10 at 16:40
  • 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 '10 at 17:57
  • ...you can always edit an answer if you have a small correction to make. Just sayin. – colithium Aug 23 '10 at 00:13
  • 1
    @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 Aug 23 '10 at 05:36
  • 5
    @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 Aug 23 '10 at 20:00
  • "You don't need to reopen the text file after writing the first line" – stepancheg Aug 23 '10 at 21:13
  • 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 Sep 05 '10 at 08:29
43

Brain***k

,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]
Lance Roberts
  • 22,383
  • 32
  • 112
  • 130
Svisstack
  • 16,203
  • 6
  • 66
  • 100
42

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.
Brock Woolf
  • 46,656
  • 50
  • 121
  • 144
Mark Mullin
  • 1,340
  • 1
  • 9
  • 21
39

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" 
arsenm
  • 2,903
  • 1
  • 23
  • 23
Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
  • 7
    Ahh the 'Almighty' Haskell. Thanks for your contribution :) – Brock Woolf Aug 21 '10 at 16:53
  • 1
    How can a side effect possible in a functional language??? People exclaim "Monad!", but I never managed to understand ... – Yuji Aug 21 '10 at 18:09
  • Yuji: "How can a side effect possibly *WHAT* in a functional language"? – Andreas Rejbrand Aug 21 '10 at 18:19
  • 3
    @Andreas Rejbrand I'm almost sure he forgot a 'be' – Federico klez Culloca Aug 21 '10 at 18:38
  • Ugh... please forgive a poor non-native English speaker:p – Yuji Aug 21 '10 at 19:42
  • 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 – Carter Tazio Schonwald Aug 22 '10 at 00: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 '10 at 07: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 '10 at 08:00
  • If only I were smart enough to understand Haskell :/ – Brock Woolf Aug 22 '10 at 08:49
  • 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 Aug 23 '10 at 23:26
  • @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 Aug 24 '10 at 06:48
35

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
  • 45,296
  • 18
  • 54
  • 69
34

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
  • 103,207
  • 26
  • 155
  • 191
  • short and sweet. thanks for your contribution. – Brock Woolf Aug 21 '10 at 16:53
  • 2
    +1 Nice, but to be strict, you don't put the input into a variable before writing it to console. – Lasse Espeholt Aug 21 '10 at 17:10
  • 3
    @lasseespeholt, you're right. I fixed it. – Wayne Conrad Aug 21 '10 at 19:56
  • 5
    No reason to uppercase varname and say 'PATH'. Just say 'path'. – OTZ Aug 22 '10 at 09: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 '10 at 10:01
  • To CONSTANT (or Constant), or not to constant, that is the question... – Wayne Conrad Aug 22 '10 at 18:16
  • 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 '10 at 21:25
  • I would get rid of the PATH constant to make it even shorter. It wouldn't be harder to read. – FelipeC Aug 24 '10 at 00:14
  • Ahh Ruby. No wonder Ruby programmers are all so superior! – Kyle Aug 24 '10 at 11:21
  • 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 Aug 24 '10 at 13:08
32

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.

Sam Holder
  • 32,535
  • 13
  • 101
  • 181
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99
29

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;
}
tchrist
  • 78,834
  • 30
  • 123
  • 180
Maister
  • 4,978
  • 1
  • 31
  • 34
  • Nice answer. Thanks for contributing +1 – Brock Woolf Aug 21 '10 at 18:35
  • Why do you call fgets() twice? – kirk.burleson Aug 22 '10 at 15:35
  • 2
    Because the second line is the one that we want to print to stdout – JeremyP Aug 22 '10 at 15:40
  • 1
    #include 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 '10 at 00:38
  • Nice clean coding (lots of decent error checking) in the orignal C post (which blows out the length somewhat). – xagyg Aug 24 '10 at 01:59
29

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

tchrist
  • 78,834
  • 30
  • 123
  • 180
robertbasic
  • 4,325
  • 1
  • 27
  • 25
27

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

Community
  • 1
  • 1
robertbasic
  • 4,325
  • 1
  • 27
  • 25
21

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
  • 176,118
  • 18
  • 189
  • 202
21

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))))
huaiyuan
  • 26,129
  • 5
  • 57
  • 63
Chris
  • 3,000
  • 26
  • 43
18

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))
Jonas
  • 19,422
  • 10
  • 54
  • 67
Abhinav Sarkar
  • 23,534
  • 11
  • 81
  • 97
18

PowerShell

sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line
Jay Bazuzi
  • 45,157
  • 15
  • 111
  • 168
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99
  • 3
    This is nice & clean. Yay powershell. – Jay Bazuzi Aug 21 '10 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). – Lasse Espeholt Aug 21 '10 at 22:08
  • 4
    Damn, is there anything shorter?? – 0fnt Aug 23 '10 at 20:11
18

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
  • 322,767
  • 57
  • 360
  • 340
17

F#

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

let secondLine = File.ReadLines path |> Seq.nth 1
printfn "%s" secondLine
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99
16

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
  • 69,683
  • 7
  • 133
  • 150
16

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
  • 46,656
  • 50
  • 121
  • 144
  • 17
    I've never liked Objective-C. The syntax just seems so foreign when coming from a language like Java. – Faisal Abid Aug 21 '10 at 17:43
  • 2
    @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 Aug 21 '10 at 18:12
  • 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 – Brock Woolf Aug 21 '10 at 19:44
  • 7
    And i thought the c++ syntax already looked the worst. – Toad Aug 21 '10 at 20:58
  • 6
    Objective-C only looks bad because the Stackoverflow syntax highlighter doesn't get coloured correctly. – Brock Woolf Aug 22 '10 at 03:44
  • 1
    You can just use `+[NSFileHandle fileHandleForUpdatingAtPath:]` so you can read and write from the same handle – Dave DeLong Aug 22 '10 at 05:20
  • @Dave Delong: Thanks for your help it looks much neater now. – Brock Woolf Aug 22 '10 at 05:37
  • Wow, looks like such a terrible language to write in. Calling it "C" is a disgrace. – Gautam Aug 23 '10 at 23:29
  • Like Mac, it's really hard to make people understand advantages of Objective-C. – eonil Aug 24 '10 at 01:39
  • 3
    @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 Aug 24 '10 at 05:42
  • 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 '10 at 11:20
  • 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 Sep 09 '10 at 19:08
  • 1
    @tml: Yes we do. Why use 50 lines of C when 8 lines of Obj-C do a much better job. – Brock Woolf Sep 10 '10 at 03:07
16

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];
tchrist
  • 78,834
  • 30
  • 123
  • 180
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
  • 15
    what about lexical filehandles, 3 argument open? – MkV Aug 21 '10 at 20:59
  • @MkV on second thought, for completeness, I added that info. Thanks for reminding me :) – Vivin Paliath Aug 21 '10 at 21:27
  • 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 '10 at 04:01
  • 4
    Same goes for two argument open: You should never use it on Stack Overflow, and probably not in practice. – rpkelly Aug 24 '10 at 01: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. – Kent Fredric Aug 24 '10 at 08:11
  • Thanks for the comments, guys. I was not aware of that best-practice. Will change it now. – Vivin Paliath Aug 24 '10 at 15:46
  • @rpkelly: You don’t need 3-arg open when you know the filename and it doesn’t contain naughty bits. – tchrist Nov 18 '10 at 19:31
  • @Ether: What you are calling lexical filehandles is incorrect. This is also a lexical filehandle: `my $handle = "STDOUT"`; Also, this is **NOT** a lexical filehandle: `our $handle = undef; open($handle, "< fileio.txt");`. Say what you really mean. – tchrist Nov 18 '10 at 19:33
  • @Vivin: I upgraded your code to a more modern form so we can provide a good and safe model for people. – tchrist Nov 18 '10 at 19:34
  • @MkV: The thing people call lexical filehandles (**WHICH AREN'T**) and even three-argument open are overhyped. If I wanted that kind of dogmatic inflexibilty, I’d be using Python. – tchrist Nov 18 '10 at 19:35
  • @RCIX: Unless you’re in a creative programming contest [like this one](http://stackoverflow.com/questions/4092348/how-to-generate-an-array-with-random-values-without-using-a-loop/4092746#4092746), Perl should *always* be easy to read! It was designed to be programmer-friendly: easy things should be easy. When Perl isn’t easy to read, you know you’ve been afflicted by a miseducated and low-skilled programmer. Bad programmers write bad code in every language. Good programmers write good code in every language. The good or bad is a reflection not fo the language but of the programmer. – tchrist Nov 18 '10 at 19:39
  • @Brock: I’ve modernized the Perl. Hope you like it. – tchrist Nov 18 '10 at 19:40
  • @Kent: thanks but no thanks. `Perl::Critic` is itself used in abominable ways. Understand the tools and their properties; don’t kowtow to the party line. Even unary `open` has its uses. – tchrist Nov 18 '10 at 19:41
  • @tchrist Thanks :) I learnt perl as I went. I remember having one code review for my code when I was interning at Motorola. But I haven't done a lot with it (other than scripts here and there). – Vivin Paliath Nov 18 '10 at 21:31
  • @tchrist: *is* there a good name for what is being aimed for here (a filehandle that is stored in a scoped variable rather than in a global)? I almost want to coin "sigiled", as for beginners it would be easy to remember that filehandles should always be stored in something that uses a leading sigil (usually `$`), but that's a bit semantically muddy too. – Ether Nov 19 '10 at 21:54
  • @Ether: If you find one, lemme know. :( It’s a terminology I’m struggling with right now myself, as you’ve doubtless correctly inferred. One *can* get a scoped filehandle through `local *FH`, or through `my $fh = \do{ local *FH }`, or simply with `local *FH = my $fh = Symbol::gensym()` (meaning, either), which is what we always used to do. I don’t find the destructor in IO::Handle auto-close()ing a convincing argument, because it muzzles any errors that close() reports, something I strongly feel is the Wrong Thing. I’d have to look at my recent programs to see what I really do. "Non-bareword"? – tchrist Nov 19 '10 at 22:21
  • @Ether: I think the best working name for those thingamjeezers is autovivved handles. – tchrist Nov 19 '10 at 23:55
  • @tchrist : sure, you can get a scoped file handle via *other* methods than using open(), just in this case, open is autovivifying a scoped file handle. The *type* of filehandle is however still "Scoped", and how you create it is unimportant. So saying 'use scoped file handles' extends beyond the 'open' clause and onto the places its used as well. It think you want to say something like "You should use open() to autovivify scoped file handles", but that is very wordy, :/. – Kent Fredric Nov 21 '10 at 19:51
  • 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 <_>; }'` – Kent Fredric Nov 21 '10 at 19:59
15

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
  • 176,118
  • 18
  • 189
  • 202
15

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());
    }       
  }
}
Mankarse
  • 39,818
  • 11
  • 97
  • 141
st0le
  • 33,375
  • 8
  • 89
  • 89
  • 36
    @Brock: These days Java is not slow. Just verbose, but not slow. Please don't make such comments; hurts us JVM people. :'| – missingfaktor Aug 21 '10 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. – NullUserException Aug 21 '10 at 18:00
  • 2
    @Missing Faktor: "slow" (by itself) doesn't mean much -- but despite improvements in performance, Java remains generally slower than some other languages. For a few examples, see: http://shootout.alioth.debian.org/u64q/benchmark.php?test=all&lang=java&lang2=gpp and: http://shootout.alioth.debian.org/u64/benchmark.php?test=all&lang=java&lang2=gcc – Jerry Coffin Aug 21 '10 at 18:02
  • 1
    @Missing Faktor you have my support :) – Mite Mitreski Aug 21 '10 at 18:05
  • 2
    Don't take it seriously guys. Java isn't slow it was only a joke. Relax :) – Brock Woolf Aug 21 '10 at 18:12
  • 1
    @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 Aug 21 '10 at 18:13
  • 2
    @Missing Faktor: why is a comparison to Smalltalk or F# "real", while a comparison to C or C++ "doesn't prove anything"? – Jerry Coffin Aug 21 '10 at 18:20
  • 4
    @Missing Faktor: And so? – Jerry Coffin Aug 21 '10 at 18:58
  • @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 Aug 21 '10 at 19:42
  • 3
    @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 Aug 21 '10 at 19:48
  • @Jerry: No further comments from me on this topic. – missingfaktor Aug 21 '10 at 19:49
  • 2
    @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 Aug 21 '10 at 20:30
  • 2
    @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 Aug 21 '10 at 20:56
  • 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) – Matt Briggs Aug 21 '10 at 21:25
  • @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 Aug 21 '10 at 21:26
  • @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 Aug 21 '10 at 21:31
  • @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 Aug 21 '10 at 21:35
  • 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. – L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳ Aug 22 '10 at 00:36
  • 3
    Java IO is slow as hell and consumes incredibly much memory. – Dave O. Aug 22 '10 at 00:54
  • 1
    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 Aug 22 '10 at 05:40
  • 2
    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 C Aug 24 '10 at 06:31
  • You forgot the encoding on input, output, and stdout. You forgot to close stdout and check for errors. You forgot that `println` cannot be used because it drops exceptions. – tchrist Nov 18 '10 at 19:10
  • @Dennis, @stOle: From the question description: `You don't need to reopen the text file after writing the first line`. And: Scanner would be more easy for input. – user unknown Apr 11 '11 at 02:30
15

R:

cat("hello\n", file="fileio.txt")
cat("world\n", file="fileio.txt", append=TRUE)
line2 = readLines("fileio.txt", n=2)[2]
cat(line2)
Noel M
  • 15,812
  • 8
  • 39
  • 47
David F
  • 1,255
  • 9
  • 12
14

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
  • 134,909
  • 25
  • 265
  • 421
  • 1
    Great! Thanks for contributing +1 – Brock Woolf Aug 21 '10 at 19:30
  • 14
    I forgot how ugly c++'s syntax can be. – Toad Aug 21 '10 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 `` just to tell `ignore` there *isn't* a limit to the line size. – Potatoswatter Aug 21 '10 at 21:45
  • 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 Aug 21 '10 at 23:28
  • 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.) – Chinmay Kanchi Aug 22 '10 at 14:02
  • 2
    Now I know why Linus says C++ is ugly. (no offense) – kizzx2 Aug 23 '10 at 17:03
  • Looks like you forgot the encoding. – tchrist Nov 18 '10 at 19:09
  • @tchrist: huh? The question does not specify an encoding. – Potatoswatter Nov 19 '10 at 07:12
  • @Potatoswatter, several times every week at work I have to fix something that happens all because somebody didn’t specify an encoding. I now consider it a bug. :( – tchrist Nov 19 '10 at 11:24
  • @tchrist: The solution is not to pick an encoding arbitrarily and specify it. The default encoding in C++ is the "C locale", which is essentially ASCII with unspecified line endings. There is no good way to specify line endings in C++ at all, and there is no other ambiguity in this program. Anyway, whatever. – Potatoswatter Nov 20 '10 at 02:19
13

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
  • 166
  • 3
12

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
  • 1,345
  • 1
  • 9
  • 11
12

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
  • 8,147
  • 5
  • 32
  • 46
  • 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 '10 at 08:17
11

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

Community
  • 1
  • 1
TheLQ
  • 14,830
  • 14
  • 69
  • 107
11

Groovy

new File("fileio.txt").with { 
    write  "hello\n"
    append "world\n"   
    println secondLine = readLines()[1]
}
kamaci
  • 72,915
  • 69
  • 228
  • 366
  • 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 '10 at 09:10
  • The 3rd clarification in the original post states "You don't need to reopen the text file after writing the first line" – Wayne Keenan Aug 22 '10 at 21:03
11

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
  • 90,905
  • 62
  • 285
  • 365
10
Rebol []

write/lines %fileio.txt "hello"
write/lines/append %fileio.txt "world"
print last read/lines %fileio.txt
Graham Chiu
  • 4,856
  • 1
  • 23
  • 41
9

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
  • 133,037
  • 18
  • 149
  • 215
9

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
  • 105,602
  • 8
  • 282
  • 384
  • Delphi reminds me of prolog for some reason :) thanks for your contribution – Brock Woolf Aug 21 '10 at 16:44
  • 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 Aug 21 '10 at 17:14
  • 9
    I think you pretty much scared everyone away from Delphi. – kirk.burleson Aug 22 '10 at 14:25
  • @Andreas: for starting of with `AssignFile`. The seventies are over. – H H Aug 23 '10 at 21:10
  • @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 Aug 23 '10 at 21:24
  • No, this not 'standard'. It is the (very) old way to do it. There is a Pascal answer here, there it is appropriate. – H H Aug 23 '10 at 21:30
  • @Henk Holterman: I always use this method... – Andreas Rejbrand Aug 23 '10 at 21:43
  • 1
    Then maybe it's time to move on to the 21st century. Use a Stream, not File/Text – H H Aug 23 '10 at 21:50
  • 2
    @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 Aug 24 '10 at 07:39
  • 1
    @Henk Holterman: "Then maybe it's time to move on to the 21st century" newer/shiner doesn't mean "better". – SigTerm Aug 25 '10 at 15:57
  • @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 Sep 19 '10 at 07:25
  • @sbi: The old way is very easy to maintain; I cannot see why any new way would be easier. – Andreas Rejbrand Sep 19 '10 at 11:26
  • 1
    @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 Sep 19 '10 at 13:31
  • @Andreas: EEK!! Is that ever long and complicated and hard to read! Plus where is the encoding specified? This isn’t the 1960s any longer: welcome to the Brave New Millennium of Unicode! – tchrist Nov 18 '10 at 19:47
  • @Andreas: What the bl**y h**l is [ANSI](http://en.wikipedia.org/wiki/American_National_Standards_Institute)??? There is no such encoding. What is it **REALLY**, and why are you calling it such a silly thing? – tchrist Nov 20 '10 at 00:05
8

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.

Brock Woolf
  • 46,656
  • 50
  • 121
  • 144
alxx
  • 9,897
  • 4
  • 26
  • 41
8

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
  • 238
  • 3
  • 7
8

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
  • 71
  • 4
  • 6
    Perl actually makes me sad. No language ever needs a keyword 'given'. What next, 'beholdeth' or 'insomuchas' – Aiden Bell Aug 22 '10 at 20:00
  • 4
    @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 Aug 23 '10 at 07:46
  • Is the .close necessary, or does the file handle fall out of scope, closing the file, at the end of the "given" block? – jplindstrom Aug 23 '10 at 23:46
  • 1
    @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 Aug 30 '10 at 06:35
  • @Aiden: What bothers you about `given`? It isn’t an archaic word like those others you mention. It’s a normal past participle of a super common verb. It’s acting as a topicalizer; I’m sure you’ll concur it’s better named for that purpose than the `foreach` that we always used to use for such, eh? – tchrist Nov 20 '10 at 00:09
8

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
  • 5,309
  • 29
  • 27
7

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 )
Brock Woolf
  • 46,656
  • 50
  • 121
  • 144
7

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
Vladimir Panteleev
  • 24,651
  • 6
  • 70
  • 114
Tcl
  • 1
  • 1
  • This is not code golf. Code should be better written for clarity instead of trying to show off terseness. – slebetman Aug 22 '10 at 15:23
  • 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 Aug 22 '10 at 15:25
7

*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
  • 62,729
  • 22
  • 87
  • 114
7

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;
}
Community
  • 1
  • 1
7

Io

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

Is this the shortest of the solutions?

6

FORTRAN

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

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

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

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

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

Rook
  • 60,248
  • 49
  • 165
  • 242
JasonFruit
  • 7,764
  • 5
  • 46
  • 61
  • Thanks for the Fortran contribution +1 – Brock Woolf Aug 21 '10 at 18:13
  • @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 Aug 22 '10 at 12:01
  • 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. – Rook Aug 22 '10 at 18:59
6

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
  • 59,062
  • 28
  • 129
  • 143
  • 4
    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). – avacariu Aug 21 '10 at 23:25
  • 2
    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 Aug 22 '10 at 10:23
  • @Vlad: Yes you are correct that is what I meant. – Brock Woolf Aug 22 '10 at 23:31
  • where is the encoding specified? – tchrist Nov 18 '10 at 19:53
6

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
Mark Bell
  • 880
  • 1
  • 12
  • 22
6

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
  • 2,514
  • 3
  • 18
  • 24
  • 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 Aug 22 '10 at 16:31
6

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
  • 1
  • 2
6

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
  • 56
  • 4
  • Is there a reason why you not `break` within `if (++lineNum == 2)`? – Lasse Espeholt Aug 22 '10 at 13:39
  • Simply because I wanted the loop to exit when the end of file was reached for sake of demonstration. – Judicium Aug 23 '10 at 13:02
  • 3
    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 Aug 24 '10 at 02:51
  • 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 Aug 25 '10 at 12:58
  • This example could be cut to a third of its length by omitting unnecessary curly braces. – sbi Sep 19 '10 at 07:27
  • 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 Sep 23 '10 at 15:40
  • @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 Sep 26 '10 at 11:45
  • @sbi: Certainly those braces need to be cuddled! – tchrist Nov 20 '10 at 00:11
6

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
  • 22,441
  • 5
  • 48
  • 71
  • MY GOODNESS but that’s unnecessarily noisy! It also has a bunch of errors. See [my modernized version](http://stackoverflow.com/questions/3538156/file-i-o-in-every-programming-language/3538321#3538321) for the right way to do this. No need for all that complexity and line noise! – tchrist Nov 18 '10 at 19:52
  • I much prefer mine thanks! Beauty is indeed in the eye of the beholder :) – draegtun Sep 15 '11 at 12:30
5

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
  • 176,118
  • 18
  • 189
  • 202
  • Lo. First language I've never heard of. Thanks for the contribution. – Brock Woolf Aug 21 '10 at 17:33
  • 8
    Actually, it's Io, with uppercase i, not Lo. :) – Ionuț G. Stan Aug 21 '10 at 17:37
  • @Brock Woolf, You were born with the knowledge of language names like C++, Java, and Haskell? – strager Aug 22 '10 at 05:39
  • Bad naming for a programming language. can't distinguish if it's 'L' or 'I'. – OTZ Aug 22 '10 at 09:15
  • 2
    @otz, Can't distinguish between ♯ and #. – strager Aug 22 '10 at 09:24
  • @strager Actually I *can*. Plus, unlike I and l, ♯ is a multibyte character, which nobody bothers to use under normal conditions. – OTZ Aug 22 '10 at 09:42
  • 1
    @otz Точно? ("Really?" in Russian. Yes, I do use multibyte characters in normal conditions.) – Catherine Aug 22 '10 at 12:38
  • I've put `Io` inside elements. Monospace fonts should make the name clear now. – Ionuț G. Stan Aug 22 '10 at 13:42
  • Not very idiomatic, that's for sure. – Justin Poliey Aug 24 '10 at 07:38
  • @Justin, feel free to edit the entry. – Ionuț G. Stan Aug 24 '10 at 09:45
  • @OTZ: There is no such thing as a multibyte character. Characters are logical integers. You must be talking about certain encodings. And remember that "I" and "l" are both multibyte characters in the UTF-16 encodings. See why your nomenclature makes no sense at all? And pretending that people are still stuck in the 1960s world of 7-bit ASCII is about 50 years out of date! Step into the Brave New Millennium, will ya please? :) – tchrist Nov 18 '10 at 19:59
  • @tchrist Wrong. A multibyte character is a character consisting of more than 1 byte in a given encoding. For example, 'あ' is represented as '\xe3\x81\x82' in UTF-8. It's a simple concept that anyone should know. – OTZ Nov 27 '10 at 08:50
  • @OTZ If you mean "when encode as UTF-8", then say that. But Unicode characters are not width-oriented. They are logical integers. It's only when you encode them that you have issues. If you use UTF-16 or UTF-32, everything is a multibyte character. Given that even with UTF-8 only 7-bit ASCII is *not* such, it doesn’t make sense to talk about it that way. People need to stop thinking of characters as having any number of bits other than what an `int` has. – tchrist Nov 27 '10 at 13:46
5

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
  • 87,344
  • 17
  • 243
  • 314
5

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
  • 3,596
  • 3
  • 29
  • 39
5

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
  • 3,003
  • 4
  • 29
  • 41
5

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
  • 21,501
  • 8
  • 58
  • 94
4

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
  • 176,118
  • 18
  • 189
  • 202
4

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
  • 192,085
  • 135
  • 376
  • 510
4

K 3

f:`fileio.txt
f 0:/:(*a;a:$`hello`world)
`0:*1_0:f
kevinlawler
  • 930
  • 1
  • 9
  • 19
  • 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. – kevinlawler Aug 23 '10 at 02:46
  • http://en.wikipedia.org/wiki/K_%28programming_language%29 – Chris Dennett Aug 23 '10 at 14:52
  • Wow, Teco (http://en.wikipedia.org/wiki/Text_Editor_and_Corrector#The_programming_language) has competition! – mike3996 Jan 09 '11 at 13:52
4

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
  • 134,909
  • 25
  • 265
  • 421
  • Don't you need to close "fileio.txt" after printing to it? Otherwise it doesn't seem to produce any output. – helpermethod Aug 22 '10 at 08:59
  • @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 Aug 22 '10 at 09:18
  • Which implementation of awk are you using? At least with gawk (GNU awk) it doesn't seem to work. This may be implementation-specific. – helpermethod Aug 22 '10 at 09:27
  • @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 Aug 22 '10 at 09:56
  • Okay, flushing also works, which is probably a lot cleaner than closing the file. – helpermethod Aug 22 '10 at 10:30
4

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
  • 3,866
  • 2
  • 24
  • 24
4

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
  • 17,124
  • 11
  • 67
  • 110
3

Boo

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

secondLine = File.ReadAllLines(path)[1]
print secondLine
st0le
  • 33,375
  • 8
  • 89
  • 89
  • 6
    Seems just like C#. ;) – st0le Aug 21 '10 at 17:51
  • 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. – Lasse Espeholt Aug 21 '10 at 22:11
3

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
  • 920
  • 1
  • 6
  • 13
3

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
avacariu
  • 2,780
  • 3
  • 25
  • 25
Chinmay Kanchi
  • 62,729
  • 22
  • 87
  • 114
  • 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? – avacariu Aug 21 '10 at 23:30
  • Yes, I only discovered this recently, but `print>>f` redirects output to any open file-like object. Thanks for the edit. – Chinmay Kanchi Aug 22 '10 at 00:52
3

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
  • 10,450
  • 1
  • 37
  • 50
3

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
  • 1,826
  • 1
  • 18
  • 19
3

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
  • 224,562
  • 31
  • 268
  • 324
3

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
  • 3,633
  • 8
  • 35
  • 43
2

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
  • 33,375
  • 8
  • 89
  • 89
2

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
  • 7,788
  • 1
  • 15
  • 5
2

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.
Abe Voelker
  • 30,124
  • 14
  • 81
  • 98
2

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
helpermethod
  • 59,493
  • 71
  • 188
  • 276
  • 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 Aug 22 '10 at 05:21
2

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
  • 87,747
  • 23
  • 163
  • 198
2

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
  • 28,421
  • 8
  • 67
  • 102
  • 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 Aug 21 '10 at 22:39
2

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
  • 5,309
  • 29
  • 27
2

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
  • 61,249
  • 84
  • 283
  • 456
1

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
  • 14,900
  • 6
  • 36
  • 74
1

SAS

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

data;
infile 'c:\fileio.txt'; 
input /; 
put _infile_;
tedc
  • 1
  • 2
1

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
  • 1,447
  • 8
  • 10
0

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

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

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

evanrmurphy
  • 1,826
  • 1
  • 18
  • 19
-7

My mind reading language

(for reference look here)

Done
Community
  • 1
  • 1
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95