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:
- Create a new text file called "fileio.txt"
- Write the first line "hello" to the text file.
- Append the second line "world" to the text file.
- Read the second line "world" into an input string.
- 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.
JavaScript - node.js
First, lots of nested callbacks.
A little bit cleaner:
Objective-C
Ruby
F#
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 theecx
which is set on line 27.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
BASIC
I haven't used BASIC in almost 10 years, but this question gave me a reason to quickly brush up my knowledge. :)