File I/O in Every Programming Language [closed]

2019-01-15 23:41发布

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.

30条回答
We Are One
2楼-- · 2019-01-16 00:04

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
查看更多
爷的心禁止访问
3楼-- · 2019-01-16 00:06

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)
}
查看更多
叛逆
4楼-- · 2019-01-16 00:07

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;
}
查看更多
Root(大扎)
5楼-- · 2019-01-16 00:07

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

查看更多
够拽才男人
6楼-- · 2019-01-16 00:08

R:

cat("hello\n", file="fileio.txt")
cat("world\n", file="fileio.txt", append=TRUE)
line2 = readLines("fileio.txt", n=2)[2]
cat(line2)
查看更多
你好瞎i
7楼-- · 2019-01-16 00:09

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" 
查看更多
登录 后发表回答