web-dev-qa-db-ja.com

すべてのプログラミング言語でのファイルI / O

これは、すべてのプログラマーが時々抱える共通の質問でなければなりません。テキストファイルから行を読み取るにはどうすればよいですか?次に、次の質問は、常にどのように書き戻すかです。

もちろん、ほとんどの人は日々のプログラミングで高レベルのフレームワークを使用します(回答で使用するのは問題ありません)が、低レベルでもそれを行う方法を知っているのはいいことです。

私自身、CC++、およびObjective-Cでそれを行う方法を知っていますが、すべての一般的な言語でそれがどのように行われるかを確認することは、より良い判断を下すためだけに役立つと確信していますファイルioをどの言語で使用するか。特に、pythonRuby、そしてもちろんPerlのような文字列操作言語でどのように実行されるかを見るのは興味深いと思います。

だから私はここでcommunity resourceを作成できると考えていますstarプロファイルに追加し、新しい言語でfile I/Oを実行する必要がある場合を参照します。露出は言うまでもなく、私たちは誰もが日常的に扱っていない言語に到達します。

これはあなたが答える必要がある方法です:

  1. fileio.txt」という新しいテキストファイルを作成します
  2. 最初の行「hello」をテキストファイルに書き込みます。
  3. 2行目の「world」をテキストファイルに追加します。
  4. 2行目の「world」を入力文字列に読み込みます。
  5. 入力文字列をコンソールに出力します。

明確化:

  • 回答ごとに1つのプログラミング言語でこれを行う方法を示す必要があります。
  • テキストファイルが事前に存在しないと仮定する
  • 最初の行を書き込んだ後、テキストファイルを再度開く必要はありません。

言語に特に制限はありません。 CC++C#JavaObjective-Cはすべて素晴らしいです。

PrologHaskellFortranLISP、またはBasicでその方法を知っている場合は、すぐに進んでください。

127
Brock Woolf

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)

明確化

  • readlines() は、ファイル内のすべての行の list を返します。したがって、readlines()を呼び出すと、ファイルの各行がすべて読み取られます。この特定のケースでは、とにかくファイル全体を読み取る必要があるため、readlines()を使用しても問題ありません(最後の行が必要です)。しかし、ファイルに多くの行が含まれていて、n行目だけを印刷したい場合は、ファイル全体を読み取る必要はありません。以下に、Pythonでファイルのn行目を取得するためのいくつかのより良い方法を示します。 Python 3のxreadlines()の代わりとなるもの

  • With with statementとは何ですか? withステートメントは、open()の呼び出しから返される stream object として変数fを使用できるコードブロックを開始します。 withブロックが終了すると、pythonはf.close()を自動的に呼び出します。これにより、withブロックを終了するときに、どのように、またはいつブロックを終了しても(未処理の例外を介して終了した場合でも)ファイルが閉じられることが保証されます。 f.close()を明示的に呼び出すこともできますが、コードで例外が発生し、f.close()呼び出しに到達しない場合はどうでしょうか?それがwithステートメントが便利な理由です。

  • 各操作の前にファイルを再度開く必要はありません。ブロック付きのコード全体を記述できます。

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

    3つの操作の違いを強調するために3つのブロックを使用しました:書き込み(モード 'w')、追加(モード 'a')、読み取り(モード 'r'、デフォルト)。

48
snakile

LOLCODE

仕様 控えめに言っても大ざっぱですが、できる限りのことをしました。ダウン投票を始めましょう! :)私はまだ楽しい運動だと思います。

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
242
Danita

脳*** k

,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]
43
Svisstack

COBOL

誰もしなかったので......

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.
42
Mark Mullin

ハスケル

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

ファイルを読み書きするだけの場合:

main :: IO ()
main = readFile "somefile.txt" >>= writeFile "someotherfile.txt" 
39
Ionuț G. Stan

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);
}
35
Bernard

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
34
Wayne Conrad

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)は.Net 4.0のみで、代替はFile.ReadAllLines(path)[1]です。これはファイル全体を配列に解析します。

33
Lasse Espeholt

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;
}
29
Maister

シェルスクリプト(UNIX)

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

実際にはsed -n "2p"部分は2行目を出力しますが、質問は2行目を変数に保存してから印刷するように要求するので、... :)

29
robertbasic

linux上のx86アセンブラー(NASM)

私は7年間asmに触れていないので、これを一緒にハックするためにgoogleを少し使わなければなりませんでしたが、それでも動作します;)私はそれが100%正しいわけではないことを知っていますが、ちょっと:D

OK、うまくいきません。これについてすみません。最後にworldを出力しますが、ファイルからは出力せず、27行目に設定されているecxから出力します。

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

使用されているリファレンス: 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

27
robertbasic

共通の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))))
21
Chris

JavaScript-node.js

まず、多くのネストされたコールバック。

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]);
                });
            });
        });
    });
});

少しクリーナー:

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)));
21
Ionuț G. Stan

シェルスクリプト

これは、以前の応答のようにsedtailなどの外部コマンドを呼び出すのではなく、組み込みコマンドのみを使用したシェルスクリプトです。

#!/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

重要なシェルスクリプトを作成するときは、別のプロセスの生成が遅くなる可能性があるため、可能な限り組み込み関数を使用することをお勧めします。私のマシンでの簡単なテストから、sedソリューションはreadを使用するよりも約20倍遅いです。この場合のようにsedを1回呼び出す場合は、それほど気にする必要はありません。気づくよりも速く実行されますが、何百または何千も実行する場合場合によっては、合計することができます。

構文に不慣れな場合は、{および}現在のシェル環境でコマンドのリストを実行(および)とは対照的に)サブシェルを作成します。現在のシェル環境で操作する必要があるため、後で変数の値を使用できます)。両方をfileio.txtからリダイレクトして作成された同じ入力ストリームで動作させるために、コマンドをグループ化する必要があります。単にread < fileio.txt; read input < fileio.txtを実行した場合、2つのコマンド間でファイルが閉じられ、再び開かれるため、最初の行が取得されるだけです。シェル構文の特異性({}はメタ文字ではなく予約語です)のため、{}を残りの部分から分離する必要がありますコマンドはスペースで、コマンドのリストは;で終了します。

read builtin は、読み込む変数の名前を引数として取ります。入力行を消費し、空白文字で入力を分割します(技術的には、$IFSの内容に従って入力を分割します。デフォルトではスペース文字になります。スペース文字は、スペース、タブ、または改行)、各単語を順番に指定された変数名に割り当て、行の残りの部分を最後の変数に割り当てます。 1つの変数を指定しているだけなので、その変数に行全体を挿入するだけです。 $input変数を再利用します。最初の行の内容を気にしないためです(Bashを使用している場合、変数名を指定することはできませんが、移植可能にするために、少なくとも1つの名前を常に指定する必要があります)。

ここで行っているように、一度に1行ずつ読み取ることができますが、より一般的なパターンは、whileループでラップすることです。

while read foo bar baz
do
  process $foo $bar $baz
done < input.txt
18
Brian Campbell

クロージュア

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

または同等に、スレッドマクロ->(かっこリムーバーとも呼ばれます)を使用します。

(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))
18
Abhinav Sarkar

パワーシェル

sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line
18
Lasse Espeholt

F#

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

let secondLine = File.ReadLines path |> Seq.nth 1
printfn "%s" secondLine
17
Lasse Espeholt

ベーシック

私はほぼ10年間BASICを使用していませんが、この質問は私の知識をすばやく磨く理由を与えてくれました。 :)

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$
16
casablanca

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]);
16
Brock Woolf

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];
16
Vivin Paliath

R:

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

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
15
Ionuț G. Stan

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());
    }       
  }
}
15
st0le

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';
}

または多少やや控えめに、

#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;
}
14
Potatoswatter

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)
}
13
eclark

アーラン

おそらく最も慣用的なアーランではありませんが、:

#!/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).
12
clofresh

Emacs LISP

Emacsは主にテキストエディタであると言う人もいますが[1]。そのため、Emacs LISPはあらゆる種類の問題を解決するために使用できますが、テキストエディターのニーズに合わせて最適化されています。テキストエディターは(明らかに)ファイルの処理方法に関して非常に特定のニーズがあるため、これはEmacs LISPが提供するファイル関連機能に影響します。

基本的に、これはEmacs LISPがファイルをストリームとして開き、部分的に読み取る機能を提供しないことを意味します。同様に、最初にファイル全体をロードせずにファイルに追加することはできません。代わりに、ファイルは完全に[2]バッファに読み込まれ[3]、編集されてからファイルに再度保存されます。

必須のタスクにはEmacs LISPを使用します。これは適切であり、同じ機能の編集を伴わない何かをしたい場合は使用できます。

ファイルに何度も追加したい場合、これには大きなオーバーヘッドが伴いますが、ここで示すように可能です。実際には、通常、手動またはプログラムでファイルに書き込む前に、バッファの変更を完了します(下の例の最初の2つのs-expressionを結合するだけです)。

(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]少なくとも、私はそれをOSと呼ぶほどには行きません。代替UIはい、OSいいえ。

[2]ファイルの一部しかロードできませんが、これはバイト単位でのみ指定できます。

[3]バッファは、文字列と「ファイルの編集中に表示されるもの」に似たデータ型です。バッファの編集中はウィンドウに表示されますが、バッファは必ずしもユーザーに表示される必要はありません。

編集:バッファに挿入されているテキストを表示する場合は、明らかにテキストを表示し、アクション間でスリープする必要があります。 Emacsは通常、ユーザーの入力を待機しているときにのみ画面を再表示します(そして、入力を待機しているのと同じではないので)また、強制的に再表示する必要があります。この例ではこれが必要です(2番目のsexpの代わりに使用します)。実際には、一度も「再表示」を使用する必要はありませんでした-はい、これはいですが...

(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"))
12
tarsius

Windowsバッチファイル-バージョン#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

最後の恐ろしいループを説明するために、ファイルにはhello(newline)ワールドのみがあると想定しています。したがって、最初の行をスキップし、2番目の行のみをエコーし​​ます。

変更ログ

  • 2-オップ、要件を誤読しなければならないか、変更された。ファイルから最後の行を読み取ります

11
TheLQ

Scala:

標準ライブラリの使用:

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)

Josh Suerethの 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)      


多くの人が同じファイル記述子を使用して2つの文字列を記述しているため、その方法も回答に含めています。

標準ライブラリの使用:

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)

Josh Suerethの 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)
11
missingfaktor

グルーヴィー

new File("fileio.txt").with { 
    write  "hello\n"
    append "world\n"   
    println secondLine = readLines()[1]
}
11
Wayne Keenan
Rebol []

write/lines %fileio.txt "hello"
write/lines/append %fileio.txt "world"
print last read/lines %fileio.txt
10
Graham Chiu

多くの言語でこの種のことを行う方法の例については(61!) Rosetta CodeのFile I/Oのページを試してください 。公平に言えば、あなたが尋ねているものに正確に答えているようには見えません-ファイル全体のI/Oを扱っています-しかし、それはこの質問が答えとして引き付ける可能性が非常に近く、より広い範囲をカバーします。

9
Donal Fellows

デルファイ

Delphi、標準の低レベルの方法(つまり、TStringListおよびその他のおもちゃなし):

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.

DelphiはネイティブのWin32コンパイラであるため、Windows APIを使用してすべてのI/O操作を処理することもできます。

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.

そして、完全を期すために、私はそれを自分では決して使用していませんが、高レベルのアプローチを含めます

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

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:これは、ファイルを明示的に閉じる必要を回避するための小さなヘルパー関数を備えた代替ソリューションです。

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.
8
ekiru

プロローグ

% 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]).
8
artificialidiot

因子

詳細情報(および最新リリースのダウンロード):

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
8
mrjbq7

ActionScript 3.0

Adobe AIRライブラリの使用:

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アプリケーションはディレクトリに書き込むことができないため、アプリケーションストレージディレクトリを使用します。

8
alxx

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;
}
7
el.pescado

* NIXシェル(bashまたはsh)

#!/bin/bash

echo 'hello' > fileio.txt
echo 'world' >> fileio.txt

myvar=`tail -n 1 fileio.txt`
echo $myvar
7
Chinmay Kanchi

ルア

io.open( 'TestIO.txt', 'w' ):write( 'hello' ):write( '\n', 'world' ):close()
aLine = io.open( 'TestIO.txt', 'r' ):read( '*a' ):match( '%C*%c*(.*)' )
print( aLine )
7
Petite Abeille

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
7
Tcl

Io

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

これは最短のソリューションですか?

7
Steve Dekorte

ムンプス(難読化されていない)

ディスク容量とメモリ使用量に関連する歴史的な理由から。 1969年、MUMPSを使用すると、コマンドを1文字(または2文字)に切り捨てることができます。そのため、Claytonの例は「奇妙」に見えました(ただし、簡単に読むことができました)。このMUMPSプログラムで何が起こっているのかについて詳しく説明します。

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
6
Sean Woods

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;
}

要約版:

void main()
{
        with (new File ("fileio.txt", File.ReadWriteCreate))
              stdout (lineOf (put("hello\n").put("world\n").rewind.text(), 1)).nl;    
}
6
doh

Streamsを使用したC#

良いC#の例は既に提供されていますが、ストリームを使用して行ごとにファイルI/Oを実行する方法を含めることも役立つと感じました。

        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);
                }
            }
        }
6
Judicium

Python 2


例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

例2-コンテキストマネージャーなし:

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
6
Corey Goldberg

現代の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!

上記は、モダンPerlでopenを使用する基本的な例です(つまり、3つの引数を開く、レキシカルファイルハンドル、オートダイ、say/printのベストプラクティス)。

ただし、$newおよび$append字句変数(ファイルハンドルを保持する)で名前空間を汚染することは本当に不要です。したがって、ポイント1〜3については、おそらくより幸せに感じるでしょう。

{ 
    open my $fh, '>', 'fileio.txt';
    say {$fh} 'hello';
}

{ 
    open my $fh, '>>', 'fileio.txt';
    say {$fh} 'world';
}

または:

use IO::File;   # core module

IO::File->new( 'fileio.txt', 'w' )->print( "hello\n" );
IO::File->new( 'fileio.txt', 'a' )->print( "world\n" );


更新 re:明確化:最初の行を書き込んだ後にテキストファイルを再度開く必要はありません

そして、2行目を読み戻すためにファイルを再度開く必要があるかどうかは言及していないので、次のようにすることができます:

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 /

6
draegtun

FORTRAN

私は最近、FORTRANが嫌いだから、ここに行く:

      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  

ldigasによる編集:一方、私はむしろそれが好き
(答えをいじって申し訳ありません。別のFortranの投稿を開始する気はありませんでした)

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

(これは少し新しいFortranのバリアントです...わずか15-20歳です;-)

6
JasonFruit

Visual Basic 6.

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
6
Mark Bell

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(),
5
OTZ

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)
5
Ionuț G. Stan

JScript(Windowsスクリプトホスト)

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);
5
Helen

J

f =: 'fileio.txt'
('hello', LF) 1!:2 < f
('world', LF) 1!:3 < f
; 1 { < ;. _2 (1!:1  < f)

最後の行はファイル(1!:1 < f)を読み取り、行に分割(< ;. _2)し、2番目の要素(1 {)を取得します。次に、Monadic ;を使用して要素のボックス化を解除します。

5
Bertrand Marron

パスカル

 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.
5
Mite Mitreski

K 3

f:`fileio.txt
f 0:/:(*a;a:$`hello`world)
`0:*1_0:f
4
kevinlawler

JavaScript-ノードのイッカク

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();

これは別の特定のJavaScript埋め込みです。

http://narwhaljs.org

4
Kris Kowal

AWK

(コマンドラインフィードバックなし)

BEGIN {
    print "hello" > "fileio.txt"
    print "world" > "fileio.txt"
    for ( i = 0; i < 2; i ++ )
        getline < "fileio.txt"
    fflush( "fileio.txt" );

    print $0
}
4
Potatoswatter

クロージュア

行ごとに読みたいので、Slurpは使用できません。

(use 'clojure.Java.io)

そして、従来のLISPスタイルで:

(let [f "hello.txt"]
  (spit f "hello\n") 
  (spit f "world\n" :append true)
  (print (second (line-seq (reader f)))))

または、最愛のブラケットを失います:

(doto "hello.txt"
  (spit "hello\n")
  (spit "world\n" :append true)
  (-> reader line-seq second print ))

PLTラケット

#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))))
4
Jason Baker

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
4
Ionuț G. Stan

CAOS

Creatures ゲームエンジンのスクリプト言語)

* 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
3
bdonlan

Python 2(代替ソリューション)

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
3
Chinmay Kanchi

MATLAB

低レベルのルーチン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);

高レベルルーチンの使用load/save/textscan/uigetfile/etc

% Load and store a matrix 
M = load('sample_file.txt') 

save filename M
3
pmod

ブー

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

secondLine = File.ReadAllLines(path)[1]
print secondLine
3
st0le

おたふく風邪

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
3
Clayton

アーク

元の提出:

(w/stdout (outfile "fileio.txt")
  prn!hello
  prn!world)
(pr:cadr:readfile "fileio.txt")

これは、2行目を追加する要件を満たしていない(継続的に書き込むのではなく)ことが指摘されました。 waterhouse これを修正し、彼のバージョンで他の改良を行います:

(w/outfile f "fileio.txt"
  (disp "hello\n" f))
(w/appendfile f "fileio.txt"
  (disp "world\n" f))
(pr:cadr:readfile "fileio.txt")

Update:この最終リビジョンは、「world」を変数に読み込まないことについて懸念があった場合に対処します。

(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))
3
evanrmurphy

コールドフュージョン

「fileio.txt」という名前の新しいテキストファイルを作成します。最初の行「hello」をテキストファイルに書き込みます。

 <cffile action="Write" file="fileio.txt" output="hello">  

2行目の「world」をテキストファイルに追加します。

<cffile action="Append" file="fileio.txt" output="world"> 

2番目の行「world」を入力文字列に読み取ります。入力文字列をコンソールに出力します。

 <cffile action="read" file="fileio.txt" variable="filecontents">
 <cfoutput>#ListLast(filecontents,Chr(13) & Chr(10))#</cfoutput>
3
Brian Bolton

プログレス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.
2
Abe Voelker

niVerse 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>

これを行うには、シーケンシャルファイル(OPENSEQ/READSEQ/WRITESEQ/CLOSESEQ)を使用するなど、他の方法があります。これは、ファイルを他のレコードと同様に扱うため、簡単な方法です。

2
Dave

小さい基本

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)
2
David Hoerster

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 }

スクリプトを実行するには

$ awk -f script.awk fileio.txt
2
helpermethod

クラシックASP/VBScript

私はこれが死にかけていることを知っていますが、まあ!

createのオプションのopenTextFileパラメーターを使用して、存在しないテキストファイルを作成できますが、長い間示しました。

これはテストされていませんが、正常に機能するはずです。

<%
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
%>
2
Tom Gullen

VBScript

Helenの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()
2
st0le

アイコン

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
2
artificialidiot

Python 3

これは、すべての出力にprintを使用し、ファイルを1回だけ開くことにより、他のバージョンとは異なります。

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)
2
dan04

SAS

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

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

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;
    }
1
Vivart

行く

// 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))
}
1
durin42

元の投稿のリンクの実行リストには、Arcのエラーがいくつかあります。修正版は次のとおりです。

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

(この修正に対するまったく新しい回答を追加して申し訳ありませんが、コメントを作成するには評判が不十分です。修正したらこれを削除してください。ありがとうございます。)

0
evanrmurphy