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条回答
不美不萌又怎样
2楼-- · 2019-01-15 23:57

PowerShell

sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line
查看更多
何必那么认真
3楼-- · 2019-01-16 00:00

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());
    }       
  }
}
查看更多
祖国的老花朵
4楼-- · 2019-01-16 00:00

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).
查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-16 00:01

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

查看更多
爷的心禁止访问
6楼-- · 2019-01-16 00:02

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.
查看更多
等我变得足够好
7楼-- · 2019-01-16 00:02

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