代码之家  ›  专栏  ›  技术社区  ›  Alistair Sutherland

每种编程语言的文件I/O[关闭]

  •  127
  • Alistair Sutherland  · 技术社区  · 7 年前

    这必须是所有程序员经常遇到的一个常见问题。 如何从文本文件中读取行?接下来的问题总是我该怎么写回去。

    当然,大多数人在日常编程中使用高级框架(在答案中可以使用),但有时知道如何在较低的级别进行编程也很好。

    我自己知道怎么做 C , C++ Objective-C 但是,如果只是帮助我们更好地决定用什么语言来做文件IO,那么看看它在所有流行语言中是如何完成的,肯定会很方便。特别是,我认为看到它在字符串操作语言中是如何完成的,会很有趣,比如: python , ruby 当然 perl .

    所以我想我们可以创建一个 社区资源 我们都可以 明星 在我们的档案里,当我们需要的时候 文件输入输出 用某种新语言。更不用说我们每天都会接触到一些我们没有接触过的语言。

    您需要这样回答:

    1. 创建一个新的文本文件,名为“ 菲利普
    2. 将第一行“hello”写入文本文件。
    3. 将第二行“world”附加到文本文件。
    4. 将第二行“world”读入输入字符串。
    5. 将输入字符串打印到控制台。

    澄清:

    • 您应该只在每个答案的一种编程语言中演示如何做到这一点。
    • 假设文本文件之前不存在
    • 写入第一行后,不需要重新打开文本文件

    语言没有特别的限制。 C , C++ , C# , Java , Objtovi-C 都很棒。

    如果你知道怎么做 Prolog , Haskell , Fortran , Lisp Basic 那就请继续。

    80 回复  |  直到 11 年前
        1
  •  48
  •   tgdavies    9 年前

    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() 返回A list 文件中的所有行。 因此,调用readlines()会导致读取文件的每一行。 在这种情况下,可以使用read line s(),因为我们无论如何都必须读取整个文件(我们需要它的最后一行)。 但是如果我们的文件包含许多行,并且我们只想打印它的第n行,那么就不需要读取整个文件。 下面是用python获取文件第n行的一些更好的方法: What substitutes xreadlines() in Python 3? .

    • 这是什么加声明? WITH语句启动一个代码块,您可以在其中使用变量F作为 stream object 从调用open()返回。 当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)
      

      我用了三个和块来强调这三个操作之间的区别: 写入(模式“w”),追加(模式“a”),读取(模式“r”,默认)。

        2
  •  242
  •   Danita    15 年前

    洛尔码

    The specs 至少可以说是粗略的,但我尽力了。让投票开始吧!我仍然觉得这是一个有趣的练习。

    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
  •  43
  •   Svisstack    15 年前

    脑***

    ,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<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>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]
    
        4
  •  42
  •   Mark Mullin    15 年前

    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.
    
        5
  •  39
  •   Calmarius    15 年前

    哈斯克尔

    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" 
    
        6
  •  35
  •   Bernard    15 年前

    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);
    }
    
        7
  •  34
  •   Wayne Conrad    15 年前

    红宝石

    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
    
        8
  •  33
  •   Lasse Espeholt    15 年前

    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] 它将整个文件解析为一个数组。

        9
  •  29
  •   Maister    15 年前

    美国国家标准委员会

    #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;
    }
    
        10
  •  29
  •   edfoh    15 年前

    shell脚本(Unix)

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

    事实上 sed -n "2p" 部分打印第二行,但问题要求将第二行存储在变量中,然后再打印,所以…:)

        11
  •  27
  •   edfoh    14 年前

    Linux上的x86汇编程序(NASM)

    我已经有7年没有接触过asm了,所以我不得不用google把它拼凑在一起,但它仍然可以工作;)我知道它不是100%正确,但是hey:d

    好吧,它不起作用。对不起。当它打印的时候 world 最后,它不会从文件中打印,而是从 ecx 设置在第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
    

    使用的参考: 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

        12
  •  21
  •   Ionuț G. Stan    15 年前

    javascript-节点.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)));
    
        13
  •  21
  •   twopoint718    15 年前

    普通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))))
    
        14
  •  18
  •   Lasse Espeholt    15 年前

    动力壳

    sc fileio.txt 'hello'
    ac fileio.txt 'world'
    $line = (gc fileio.txt)[1]
    $line
    
        15
  •  18
  •   Brian Campbell    15 年前

    外壳脚本

    下面是一个仅使用内置命令的shell脚本,而不是调用外部命令,例如 sed tail 就像以前的回答一样。

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

    在编写重要的shell脚本时,建议尽可能多地使用内置脚本,因为生成单独的进程可能会很慢;从我的计算机上的快速测试来看, 塞德 解决方案比使用慢20倍 read . 如果你要打电话 塞德 一旦,就像在这种情况下一样,它实际上并不重要,因为它的执行速度比你能注意到的要快,但是如果你要执行成百上千次,它可以加起来。

    对于不熟悉语法的人, { } execute a list of commands in the current shell environment (而不是 ( ) 它创建了一个子shell;我们需要在当前shell环境中操作,以便稍后可以使用变量的值)。我们需要将这些命令组合在一起,以便让它们都在相同的输入流上操作,这是通过从 fileio.txt 如果我们只是跑 read < fileio.txt; read input < fileio.txt 我们将得到第一行,因为文件将在两个命令之间关闭并重新打开。由于shell语法的特殊性( { } 是保留字,而不是元字符),我们需要将 { } 从其余带有空格的命令中,用 ; .

    这个 read builtin 将要读取的变量名作为参数。它使用一行输入,用空格分隔输入(从技术上讲,它根据 $IFS ,默认为空格字符,其中空格字符表示将其拆分到空格、制表符或换行符中的任何一个上),将每个单词指定给按顺序给定的变量名,并将行的其余部分指定给最后一个变量。因为我们只提供一个变量,所以它只将整行内容放在这个变量中。我们重用 $input 变量,因为我们不关心第一行的内容(如果我们使用bash,那么就不能提供变量名,但要便于移植,必须始终提供至少一个名称)。

    请注意,虽然您可以像我在这里所做的那样一次读取一行,但更常见的模式是将其包装在while循环中:

    while read foo bar baz
    do
      process $foo $bar $baz
    done < input.txt
    
        16
  •  18
  •   Abhinav Sarkar    15 年前

    克洛杰尔

    (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))
    
        17
  •  17
  •   Lasse Espeholt    15 年前

    弗斯

    let path = "fileio.txt"
    File.WriteAllText(path, "hello")
    File.AppendAllText(path, "\nworld")
    
    let secondLine = File.ReadLines path |> Seq.nth 1
    printfn "%s" secondLine
    
        18
  •  16
  •   casablanca    15 年前

    基本的

    我已经有近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$
    
        19
  •  16
  •   Alistair Sutherland    15 年前

    Objtovi-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]);
    
        20
  •  16
  •   Skittles    15 年前

    珀尔

    #!/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];
    
        21
  •  15
  •   Igorekk    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)
    
        22
  •  15
  •   Calmarius    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
    
        23
  •  15
  •   gclj5    14 年前

    爪哇

    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());
        }       
      }
    }
    
        24
  •  14
  •   steffenj    15 年前

    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;
    }
    
        25
  •  13
  •   eclark    15 年前

    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)
    }
    
        26
  •  12
  •   clofresh    15 年前

    二郎

    可能不是最惯用的二郎,但:

    #!/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).
    
        27
  •  12
  •   Thiago Silva    15 年前

    Emacs Lisp

    尽管有人说emacs主要是一个文本编辑器[1]。因此,虽然EmacsLisp可以用于解决各种问题,但它是针对文本编辑器的需要而优化的。由于文本编辑器(显然)在处理文件的方式上有相当特殊的需求,这会影响EmacsLisp提供的与文件相关的功能。

    基本上,这意味着EmacsLisp不提供将文件作为流打开并逐个读取的函数。同样,如果不先加载整个文件,就不能追加到文件。相反,文件完全被[2]读取到缓冲区[3]中,编辑后再次保存到文件中。

    对于必须执行的任务,您将使用EmacsLisp,因为这是合适的,如果您想做一些不涉及编辑的事情,可以使用相同的函数。

    如果您想一次又一次地附加到一个文件中,这会带来巨大的开销,但正如这里所演示的,这是可能的。在实践中,通常在写入文件之前手动或以编程方式完成对缓冲区的更改(只需将下面示例中的前两个s表达式组合在一起)。

    (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]至少我不会把它称为操作系统;一个可选的用户界面是的,一个操作系统否。

    [2]您只能加载文件的部分内容,但只能按字节顺序指定。

    [3]缓冲区在某种程度上既类似于字符串,又类似于“编辑文件时看到的东西”。编辑缓冲区时,缓冲区显示在窗口中,但用户不必看到缓冲区。

    编辑:如果希望看到插入缓冲区的文本,显然必须使其可见,并在操作之间休眠。因为Emacs通常只在等待用户输入时重新显示屏幕(睡眠与等待输入不同),所以您还必须强制重新显示。在这个例子中这是必要的(用它来代替第二性别);在实践中,我从来没有用过“重新显示”一次——所以是的,这很难看,但是……

    (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"))
    
        28
  •  11
  •   TheLQ    15 年前

    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-对了,一定是误读了要求,或者是我的要求变了。现在从文件中读取最后一行

        29
  •  11
  •   Ricardo Acras    15 年前

    斯卡拉:

    使用标准库:

    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)      
    


    因为很多人都用同一个文件描述符来写这两个字符串,所以我的答案中也包括了这个方法。

    使用标准库:

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

    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)
    
        30
  •  11
  •   sweets-BlingBling    14 年前

    格罗维

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