每种编程语言中的文件I/O.

Bro*_*olf 127 language-agnostic file-io programming-languages

这必须是所有程序员不时有的常见问题.如何从文本文件中读取一行?然后下一个问题是我如何写回来.

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

我自己知道该怎么做的C,C++以及Objective-C,但它肯定会得心应手,看看它是如何在所有流行的语言来完成,如果仅仅是为了帮助我们做出什么语言来尽我们的文件IO在一个更好的决定.特别是我认为这将是有趣的,看看它是如何在字符串操作语言完成,如:python,ruby当然perl.

所以我想在这里我们可以创建一个社区资源,我们可以为我们的配置文件加注星标,并参考我们何时需要以某种新语言进行文件I/O. 更不用说曝光我们都会得到我们日常不处理的语言.

这是你需要回答的方式:

  1. 创建一个名为" fileio.txt " 的新文本文件
  2. 将第一行"hello"写入文本文件.
  3. 将第二行"world"附加到文本文件.
  4. 将第二行"world"读入输入字符串.
  5. 将输入字符串打印到控制台.

澄清:

  • 您应该仅针对每个答案以一种编程语言显示如何执行此操作.
  • 假设文本文件事先不存在
  • 写完第一行后,无需重新打开文本文件

对语言没有特别限制. C,C++,C#,Java,Objective-C都是伟大的.

如果你知道如何做到这一点的Prolog,Haskell,Fortran,Lisp,或Basic则请请便.

Dan*_*ita 242

LOLCODE

规格至少可以说是粗略的,但我尽我所能.让downvoting开始吧!:)我仍然觉得这是一个有趣的运动.

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
Run Code Online (Sandbox Code Playgroud)

  • 难道我觉得LOLCODE比我见过的任何其他东西都更具可读性吗? (85认同)
  • 我不认为有任何其他语言可以让这个属性,从字面上,让我...哈哈. (28认同)
  • 说你期望被投票是对SO的支持的保证,因为逆向心理学是程序员的反射行为. (19认同)
  • 这是一种自然语言的感觉. (13认同)
  • PLZ?/ AWSUM THX/O NOES非常棒.这对我来说似乎有点万能. (13认同)
  • 我原本期望LOLCODE使用基于单一的索引,因为这对小型小猫来说更自然. (3认同)
  • 我实际上想象一些人或者一些孩子在输入时大声读出这段代码."好的,我会写这个程序......"打开编辑:"嗨,我能有一个标准的IO"这里他很无聊,因为他用这些线开始他所有的程序."嗯......拜托,打开文件...... mmmm ......'文件'......"他点击进入这里并说了一点赞美:"太棒了,谢谢!" 等等... (2认同)
  • @Joel:小心说!经理可能会无意中听到你的意图,并要求用它来代替旧的Cobol应用程序,然后我们几十年都会坚持使用它. (2认同)

sna*_*ile 48

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)
Run Code Online (Sandbox Code Playgroud)

澄清

  • readlines()返回文件中所有行的列表.因此,readlines()的调用导致读取文件的每一行.在那种特殊情况下,使用readlines()是很好的,因为我们必须要读取整个文件(我们想要它的最后一行).但是如果我们的文件包含很多行而我们只想打印它的第n行,则不必读取整个文件.下面是一些在Python中获取文件第n行的更好方法:什么替代Python 3中的xreadlines()?.

  • 这是什么声明?with语句启动一个代码块,您可以在其中使用变量f作为从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)
    
    Run Code Online (Sandbox Code Playgroud)

    我用三个块来强化三个操作之间的区别:写(模式'w'),追加(模式'a'),读(模式'r',默认).

  • 我真的不认为任何人都应该在示例代码中编写`readlines()[1]`.在这种情况下,您可能知道该文件只有两行,但其他人轻率地假设它是一个很好的解决方案可能会在百万行文件上尝试它并得到一个相当令人讨厌的惊喜. (19认同)
  • @Porculus with readlines()我们不会遍历文件中的所有行.这是python 3. readlines()返回一个迭代器(不是列表).因此,只会读取文件的前两行.这类似于python 2中的xreadlines()(在python 3中不存在). (14认同)
  • @SilentGhost我引用"Dive into Python 3":"readlines()方法现在返回一个迭代器,因此它与Python 2中的xreadlines()一样有效".在以下网址搜索此声明:http://diveintopython3.org/porting-code-to-python-3-with-2to3.html.其次,在python 3中,您可以索引迭代器.shell中的类型范围(10)[4](range()也返回Python 3中的迭代器,与python 2相反,其中range()返回一个列表).注意,范围(N)[i]在O(i)中完成,而不是O(1)而不是O(N). (8认同)
  • @snakile:请你引用一些东西来支持*`readlines()`返回一个迭代器(不是列表)*只是注意:你通常不能索引迭代器. (7认同)
  • @snakile:您的评论在几个层面上都是错误的.首先,readlines返回Python 3中的列表(测试并查看).所以给出的代码将读取整个文件.其次,迭代器不能在Python 2或3中编入索引.`range`对象特别支持索引,这在O(1)中完成. (5认同)
  • @Porculus,@ SunnyGhost,@ interjay,@ colithium,感谢您的发言.readlines()我错了(好吧,我只是跟着"潜入python"的错误).我在答案中添加了澄清说明.抱歉在互联网上出错了. (5认同)
  • 蟒蛇.整洁,优雅,简洁.感谢您的贡献. (3认同)
  • 是`with`是一种帮助你处理资源的结构?或者那是为了什么? (2认同)
  • @notJim:with语句启动一个代码块,您可以使用变量f(或任何其他变量)作为从open()调用返回的流对象.当with块结束时,python会自动调用f.close().无论您何时或何时退出该块,即使您通过未处理的异常退出,也会在退出with块时关闭该文件.你可以显式地调用f.close(),但是如果你的代码引发异常并且你没有进入f.close()调用怎么办?这就是with语句有用的原因. (2认同)

Svi*_*ack 43

脑***ķ

,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]
Run Code Online (Sandbox Code Playgroud)

  • 你错过了' - '吗?;) (26认同)
  • 哦,努力.只是为了记录,写了多少时间? (2认同)

Mar*_*lin 42

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.
Run Code Online (Sandbox Code Playgroud)

  • 在家里尝试时要小心.您的cobol编译器可能不喜欢这些现代可变长度线... (3认同)
  • 对于纯粹的真棒+1,这应该被投票不少于100万次 (2认同)

Ion*_*tan 39

哈斯克尔

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
Run Code Online (Sandbox Code Playgroud)

如果您只想读/写文件:

main :: IO ()
main = readFile "somefile.txt" >>= writeFile "someotherfile.txt" 
Run Code Online (Sandbox Code Playgroud)

  • 啊'全能'哈斯克尔.谢谢你的贡献:) (7认同)
  • 在Haskell中有许多其他基本I/O方法,一旦你在做某些类型的应用程序,它们在Haskell中变得有用/重要.cabal/hackage上的text和bytestring包允许您处理各种编码,各种iteratee样式包(例如iteratee和enumerate)代表了用于执行增量io的"最着名的抽象".同样重要的是解析像parsec这样的lib和只有attoparsec lib的增量字节串.Haskellers采用了非常彻底的方法来探索io设计选择.不可行的例子包括懒惰的io和延续 (4认同)
  • Yuji:基本上是通过作弊.Haskell是一种纯函数式语言,*除了*之外的任何类型`IO a`,它具有对副作用的特殊编译器支持.(纯度在其他地方保留,因为*执行或观察副作用的任何*都是'IO a`类型,因此类型系统确保程序的其余部分保持纯净.) (4认同)
  • 碰巧"IO"是一个monad,但这并不是为什么允许它做副作用的原因.作为一个monad是让你编写看起来具有命令性的语法的东西:它还确保(也有特殊的语言支持)副作用以合理的顺序发生,所以你在写入之前不要从文件中读取,等等. (4认同)
  • @Andreas Rejbrand我几乎可以肯定他忘记了'是' (3认同)

Ber*_*ard 35

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);
}
Run Code Online (Sandbox Code Playgroud)

  • +1,比C++版本更美观,更可读!我梦想有一天D完全取代C和C++.:-) (10认同)
  • 尼斯.也许有一天我应该学习D. (10认同)

Way*_*rad 34

红宝石

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
Run Code Online (Sandbox Code Playgroud)

  • 没有理由大写varname并说'PATH'.只要说'路径'. (5认同)
  • @lasseespeholt,你是对的.我修好了它. (3认同)
  • +1很好,但要严格,在将其写入控制台之前,不要将输入放入变量中. (2认同)
  • @otz这是一个常数.他本可以称之为'Path',Ruby中的常量只需要以大写字母开头. (2认同)

Las*_*olt 33

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);
Run Code Online (Sandbox Code Playgroud)

File.ReadLines(path).ElementAt(1)仅限.Net 4.0,替代方案是File.ReadAllLines(path)[1]将整个文件解析为数组.

  • 注意:File.ReadLines特定于.NET 4 (13认同)
  • C#有多令人不快的语法 (5认同)
  • 为什么要downvote?请评论 (4认同)
  • @Aiden Bell:相对于哪种语言? (3认同)
  • @Aiden Bell - 这个答案试图简洁可读.在C#中有很多"很好"的方法可以实现同样的功能.有关更实际的示例,请参见http://dotnetperls.com/file-handling. (2认同)

Mai*_*ter 29

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 因为第二行是我们要打印到stdout的那一行 (2认同)

小智 29

Shell脚本(UNIX)

#!/bin/sh
echo "hello" > fileio.txt
echo "world" >> fileio.txt
LINE=`sed -ne2p fileio.txt`
echo $LINE
Run Code Online (Sandbox Code Playgroud)

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

  • 我不知道为什么,但我喜欢这个:) (9认同)

小智 27

Linux上的x86汇编程序(NASM)

我没有在7年内触及asm,所以我不得不使用谷歌一起破解这个,但仍然,它有效;)我知道它不是100%正确,但嘿:D

好的,它不起作用.抱歉,这个.虽然它world最后打印,但它不会从文件中打印出来,而是从第ecx27行设置.

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
Run Code Online (Sandbox Code Playgroud)

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

  • 有趣的是C中的例子,应该是一个更高级别的语言,大约和这个一样长... =) (4认同)

Ion*_*tan 21

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]);
                });
            });
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

有点清洁:

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)));
Run Code Online (Sandbox Code Playgroud)

  • 这段代码迫切需要延续.我能听到它的眼泪. (5认同)
  • @Dave,它不是浏览器中的JS.我的意思是,在语法和语义上,它是相同的JS,只是标准库是不同的.我使用了`node.js`平台的stdlib.见http://nodejs.org/ (4认同)
  • 线下的数量几乎与楼下的ASM解决方案相匹配,这不是很有趣吗? (2认同)

Chr*_*ris 21

Common 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))))
Run Code Online (Sandbox Code Playgroud)


Abh*_*kar 18

Clojure的

(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)))))
Run Code Online (Sandbox Code Playgroud)

或者等效地,使用线程宏->(也称为paren remover):

(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))
Run Code Online (Sandbox Code Playgroud)

  • 等等,`spit`实际上是写文件功能的名称? (11认同)
  • Clojure绝对不会摇滚! (4认同)
  • 当然,@ kirk.burleson比Java还要多.:) (4认同)

Las*_*olt 18

电源外壳

sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line
Run Code Online (Sandbox Code Playgroud)

  • 该死的,还有什么更短的吗? (4认同)
  • 这很干净.Yay powershell. (3认同)

Bri*_*ell 18

Shell脚本

下面是使用只是内置命令,而不是调用外部命令,如shell脚本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
Run Code Online (Sandbox Code Playgroud)

在编写重要的shell脚本时,建议尽可能使用内置函数,因为生成一个单独的进程可能会很慢; 通过在我的机器上进行快速测试,该sed解决方案比使用速度慢约20倍read.如果你打算打电话sed一次,就像在这种情况下一样,它并不重要,因为它会比你注意到的更快地执行,但是如果你要执行数百或数千次,它可以加起来.

对于那些不熟悉的语法,{} 执行命令的列表在当前shell环境(相对于()其创建子外壳;我们需要在当前外壳环境中操作,因此,我们稍后可以使用变量的值) .我们需要将命令组合在一起,以使它们都在相同的输入流上操作,通过重定向来创建fileio.txt; 如果我们只是简单地运行read < fileio.txt; read input < fileio.txt,我们就会得到第一行,因为文件将被关闭并在两个命令之间重新打开.由于shell语法的特殊性({并且}是保留字,而不是元字符),我们需要分离{}从带有空格的其余命令开始,并用a终止命令列表;.

read内置带一个参数变量的名字读入.它消耗了一行输入,打破了空格的输入(从技术上讲,它根据内容突破它$IFS,默认为空格字符,空格字符意味着将它分隔在任何空格,制表符或换行符上),指定每个单词以顺序给出的变量名称,并将该行的其余部分分配给最后一个变量.因为我们只提供一个变量,所以它只是将整行放在该变量中.我们重用$input变量,因为我们不关心第一行是什么(如果我们使用Bash,我们可能不提供变量名,但为了便携,你必须始终提供至少一个名称).

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

while read foo bar baz
do
  process $foo $bar $baz
done < input.txt
Run Code Online (Sandbox Code Playgroud)

  • 非常好.我学到了一些东西(虽然是暂时的). (3认同)

Las*_*olt 17

F#

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

let secondLine = File.ReadLines path |> Seq.nth 1
printfn "%s" secondLine
Run Code Online (Sandbox Code Playgroud)


cas*_*nca 16

BASIC

我差不多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$
Run Code Online (Sandbox Code Playgroud)


Bro*_*olf 16

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]);
Run Code Online (Sandbox Code Playgroud)

  • 我从来都不喜欢Objective-C.当来自像Java这样的语言时,语法似乎很陌生. (17认同)
  • 我认为c ++语法已经看起来最糟糕了. (7认同)
  • Objective-C看起来很糟糕,因为Stackoverflow语法高亮显示器没有正确着色. (6认同)
  • Objective-C的秘诀在于Xcode为您完成所有代码完成.您不必记住长方法名称.它们肯定会使您的代码更具可读性 (5认同)
  • 我无法相信这是如此遥远的名单!此外,Java家伙评论说Objective-C很难看,你看到写同一个文件花了多少行?我曾经是一名Java爱好者,但我认为Objective-C已经悄悄进入我的心中. (4认同)
  • @ Gautam,@ Eonil:感谢Obj-C的抨击.它只是表明你的无知和有限的技能作为一个程序员,当谈到你所知道的一种语言不同的东西. (3认同)
  • @Faisal:Obj-C非常接近Java:无论如何它们都是命令式的,面向对象的语言.你会被Prolog等感到震惊,它有着完全不同的心态. (2认同)

Viv*_*ath 16

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];
Run Code Online (Sandbox Code Playgroud)

  • 那个lexical filehandles,3个参数打开了吗? (15认同)
  • 不应在Stack Overflow上使用非词法文件句柄.在实践中很少需要它们,并且不应该向初学者证明它们甚至存在. (6认同)
  • 我可以阅读...;) (4认同)
  • 两个参数打开也是如此:你永远不应该在Stack Overflow上使用它,而且可能不会在实践中使用它. (4认同)
  • 我使用3-arg open和lexical文件句柄这么多,当我看到它时,我几乎认为它是语法错误.应该如此./我思考写一个模块来实现它. (2认同)
  • "即使是一元开放也有它的用途",它有它的用途,是的,但是当我弄清楚它是如何工作的那一天我感到被虐待,并且每当我看到有人认为他们需要它时,它肯定会有"另一种方式".`perl -we'for(q {ps aux |}){open _; print <_>; }'` (2认同)

Ion*_*tan 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
Run Code Online (Sandbox Code Playgroud)

  • 或者,您可以采用C实现并添加美元符号. (20认同)
  • 为了防止任何人感到好奇,他离开结束标记的原因是因为如果你包含它,并留下任何尾随空格,你就有可能收到"已发送标题"错误. (6认同)

st0*_*0le 15

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());
    }       
  }
}
Run Code Online (Sandbox Code Playgroud)

  • @Brock:这些天Java并不慢.只是冗长,但并不慢.请不要发表这样的评论; 伤害了JVM人.:"| (36认同)
  • 执行速度是程序员最沮丧的形式.它始终是为工作选择合适的工具,选择一个随机的指标,如执行速度,并为其分配重要的堆,这是愚蠢的,特别是因为执行速度对于绝大多数任务来说并不是非常重要,只要它足够快(几乎所有的东西都是java) (19认同)
  • "硬连接比机器代码更快","机器代码比asm快","asm比C更快","C比Java快","等等等等等等......"你甚至有一个线索有多少间接已经在机器代码和CPU之间?微码,预测优化器,指令/数据缓存,解码器等,更不用说由C/asm中的动态分配引起的非确定性.Java和其他安全语言只是间接的一小步,这没什么大不了的.你可以永远保持原始形式,也可以与我们一起发展. (11认同)
  • 无论谁说Java速度慢,要么是盲目的Java仇恨,要么生活在摇滚之下.如果不比C快,Java可以与平台独立性一样快地启动. (9认同)
  • @Missing Faktor:等等? (4认同)
  • @Jerry:正如Paul Biggar所说[这里](http://stackoverflow.com/questions/1517868/performance-of-java-1-6-vs-c/1517874#1517874),"哪个(alioth stats)应该是首先,你可以随意编写程序.我知道haskell做得很好,但代码不是惯用的,所以你从未使用的廉价技巧出来了.其次,它只使用微小的程序很少有趣的Java和C++程序少于10000行代码.许多代码大于100万个LOC." 事实上,人们普遍认为Java可以与C或C++一样快(有时甚至更快). (3认同)
  • Java IO很慢,耗费了大量的内存. (3认同)
  • @Missing Faktor:"慢"(单独)并不意味着什么 - 但尽管性能有所提高,但Java仍然比其他语言慢.有关几个示例,请参阅:http://shootout.alioth.debian.org/u64q/benchmark.php?test = all&lang = java&lalang2 = gpp和:http://shootout.alioth.debian.org/u64/benchmark. PHP?测试=所有&LANG = Java和LANG2 = GCC (2认同)
  • 不要把它当回事.Java并不慢,这只是一个笑话.放松 :) (2认同)
  • @Missing Faktor:为什么要比较Smalltalk或F#"real",而与C或C++的比较"并不能证明什么"? (2认同)
  • @Missing Faktor:没有基准是100%准确的.然而,实际上,他们可能会以不切实际的*有利的方式展示Java.首先,大多数使用小循环的多次迭代 - 最小化JIT编译所花费的时间,但最大化其效果.其次,大多数只运行很短的时间,最大限度地减少(通常消除)垃圾收集所花费的时间.国际海事组织,"100万LOC"大多是一种廉价的策略,使得它a)不合理的任何人要求你备份索赔,并且b)他们不太可能能够证明客观证据你错了. (2认同)
  • @Jerry:因为java和C#/ F#被编译成某种形式的中间语言,而不是直接原生.C和C++通过直接编译为机器代码而有所提升. (2认同)
  • 一个较短的版本,如果你感兴趣的话(新的FileWriter("fileio.txt"){{write("hello \n");}}).close(); (new FileWriter("fileio.txt",true){{write("world \n");}}).close(); (new LineNumberReader(new FileReader("fileio.txt")){{setLineNumber(2); System.out.println(readLine());}}).close(); (2认同)

Dav*_*d F 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)


Pot*_*ter 14

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';
}
Run Code Online (Sandbox Code Playgroud)

或者有点不那么迂腐

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我忘了c ++的语法有多丑. (14认同)
  • @Hans:你想澄清一下吗?就个人而言,我认为I/O _belongs_在库中而不是在语言中,我编程的所有语言都是这样做的(C,C++,Java,Python等) (8认同)
  • 现在我知道为什么Linus说C++很难看.(没有冒犯的意思) (2认同)

小智 13

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)
}
Run Code Online (Sandbox Code Playgroud)

  • 该语言应重命名为"type" (23认同)
  • 令人惊讶的是,经过30年的演变和语言设计,他们仍然设法发明了一种新的语言,就像C一样难以编写错误检查代码.甚至Java也不那么冗长! (16认同)
  • 哇......看起来很糟糕这个例子失败了 (5认同)
  • 去:没有'尝试' (2认同)

clo*_*esh 12

二郎神

可能不是最惯用的Erlang,但是:

#!/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).
Run Code Online (Sandbox Code Playgroud)


tar*_*ius 12

Emacs Lisp

尽管有些人说Emacs主要是文本编辑器[1].因此,虽然Emacs Lisp可用于解决各种问题,但它可以针对文本编辑器的需求进行优化.由于文本编辑器(显然)在处理文件的方式方面有非常特殊的需求,这会影响Emacs Lisp提供的文件相关功能.

基本上这意味着Emacs Lisp不提供以文件形式打开文件的功能,并逐个阅读.同样,如果不先加载整个文件,就无法附加到文件中.而是将文件完全[2]读入缓冲区[3],进行编辑,然后再次保存到文件中.

对于必须完成的任务,你可以使用Emacs Lisp这是合适的,如果你想做一些不涉及编辑的东西,可以使用相同的功能.

如果你想一遍又一遍地附加到一个文件,这会带来巨大的开销,但这可能如此处所示.在实践中,您通常在写入文件之前手动或以编程方式完成对缓冲区的更改(只需在下面的示例中组合前两个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))))
Run Code Online (Sandbox Code Playgroud)

[1]至少我不会把它称为操作系统; 替代UI是,操作系统没有.

[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"))
Run Code Online (Sandbox Code Playgroud)


The*_*eLQ 11

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
Run Code Online (Sandbox Code Playgroud)

为了解释最后一个可怕的寻找循环,它假设文件中只有hello(换行符)世界.所以它只是跳过第一行,只回过第二行.

更新日志

  • 2 - Opps,必须误读要求或改变我.现在从文件中读取最后一行


小智 11

Groovy的

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

  • 你是在欺骗"世界"部分.它没有附加,它只是写入相同的文件描述符. (3认同)

mis*_*tor 11

斯卡拉:

使用标准库:

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)
Run Code Online (Sandbox Code Playgroud)

使用Josh Suereth的Scala-ARM库:

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)      
Run Code Online (Sandbox Code Playgroud)

由于很多人使用相同的文件描述符来编写两个字符串,所以我在答案中也包含了这种方式.

使用标准库:

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)
Run Code Online (Sandbox Code Playgroud)

使用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)
Run Code Online (Sandbox Code Playgroud)

  • @Radtoo:必须显示追加操作.这就是我这样做的原因. (2认同)

Gra*_*hiu 10

Rebol []

write/lines %fileio.txt "hello"
write/lines/append %fileio.txt "world"
print last read/lines %fileio.txt
Run Code Online (Sandbox Code Playgroud)


Don*_*ows 9

对于如何做这种事情的例子很多语言(61!)尝试对文件I/O页面罗塞塔代码.公平地说,它似乎并没有准确地回答你所要求的 - 它正在处理整个文件I/O--但它非常接近并且覆盖范围更广,否则这个问题可能会作为答案吸引.

  • 只是为了纪录--61!= 5075802138772247988008568121766252272260045289880360030994059394809856 00000000000000 (34认同)
  • @Belisarius:你不是说 - 61!= - 50758 ...... (17认同)
  • 你确定你不是指61,而不是61!? (8认同)
  • @belisarius非常感谢你将一个零块移到右边 - 使整个数字突然完全可读. (7认同)

And*_*and 9

德尔福

德尔福,标准,低级方式(即没有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.
Run Code Online (Sandbox Code Playgroud)

因为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.
Run Code Online (Sandbox Code Playgroud)

而且,为了完整起见,我包括了高级方法,即使我自己从不使用它:

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.
Run Code Online (Sandbox Code Playgroud)

  • 我觉得你几乎让所有人都害怕德尔福. (9认同)
  • @Henk Holterman:为什么放弃一个完美的工作系统?低级方法速度快(速度快),非常易于使用,完全无限制,因为它可以让您完全控制.也许我应该补充一点,我比文本文件更频繁地读/写二进制文件,而当谈到二进制文件时,没有那么多替代低级方法.因此,即使对于文本文件,我总是习惯使用它.但仍然:为什么放弃一种完美的方法呢?我知道有些人害怕低级,手工,东西,但我不是. (2认同)

alx*_*lxx 8

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

由于安全原因,AIR应用程序无法写入其目录,因此它使用应用程序存储目录.


mrj*_*bq7 8

因子

有关更多信息(以及下载最新版本):

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
Run Code Online (Sandbox Code Playgroud)


eki*_*iru 8

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.
Run Code Online (Sandbox Code Playgroud)

编辑:这是一个带有小辅助函数的替代解决方案,以避免显式关闭文件.

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.
Run Code Online (Sandbox Code Playgroud)

  • Perl实际上让我难过.没有语言需要关键字"给定".接下来是什么,'beholdeth'或'insomuchas' (6认同)
  • @Aiden:Perl 6中的`given`类似于Clojure的`doto`宏.它允许您避免重复调用方法的对象的名称. (4认同)

art*_*iot 8

序言

% 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]).
Run Code Online (Sandbox Code Playgroud)


小智 7

LUA

io.open( 'TestIO.txt', 'w' ):write( 'hello' ):write( '\n', 'world' ):close()
aLine = io.open( 'TestIO.txt', 'r' ):read( '*a' ):match( '%C*%c*(.*)' )
print( aLine )
Run Code Online (Sandbox Code Playgroud)


小智 7

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
Run Code Online (Sandbox Code Playgroud)


Chi*_*chi 7

*NIX shell(bash或sh)

#!/bin/bash

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

myvar=`tail -n 1 fileio.txt`
echo $myvar
Run Code Online (Sandbox Code Playgroud)


el.*_*ado 7

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;
}
Run Code Online (Sandbox Code Playgroud)


小智 7

Io

File with("fileio.txt") open write("hello\n") write("world\n") \
    rewind readLines second println
Run Code Online (Sandbox Code Playgroud)

这是最短的解决方案吗?


Jas*_*uit 6

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  
Run Code Online (Sandbox Code Playgroud)

由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
Run Code Online (Sandbox Code Playgroud)

(这是一个较新的Fortran变种......只有15-20岁左右;-)


Cor*_*erg 6

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
Run Code Online (Sandbox Code Playgroud)

示例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
Run Code Online (Sandbox Code Playgroud)

  • 这完全遵循规则吗?这会将`hello`和`world`附加到文件中.规则说`hello`必须写入文件,并且应该附加`world`.除非这被接受......(我不太清楚OP的含义). (4认同)
  • 你可以使用`f.next();而不是读取整个文件的`f.readlines()[1]`.s = f.next()`它只读取前两行.或者使用itertools.islice(f,1,2)[0] (2认同)

Mar*_*ell 6

Visual Basic 6.0

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
Run Code Online (Sandbox Code Playgroud)


Sea*_*ods 6

MUMPS(未混淆)

由于与磁盘空间和内存使用相关的历史原因.1969年,MUMPS允许你将命令截断为一个(或有时两个)字符,这就是为什么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
Run Code Online (Sandbox Code Playgroud)


小智 6

D与探戈

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;
}
Run Code Online (Sandbox Code Playgroud)

简明版:

void main()
{
        with (new File ("fileio.txt", File.ReadWriteCreate))
              stdout (lineOf (put("hello\n").put("world\n").rewind.text(), 1)).nl;    
}
Run Code Online (Sandbox Code Playgroud)


Jud*_*ium 6

C#with Streams

之前已经提供了一个很好的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);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

  • 你有没有理由这样做... StreamWriter writer = File.CreateText(path); writer.WriteLine( "你好"); writer.Close(); 而不是更惯用的...使用(StreamWriter writer = File.CreateText(path))writer.WriteLine("Hello"); using语句应该用于管理一次性资源,而不是手动处理可能导致泄漏的资源. (3认同)

dra*_*tun 6

现代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!
Run Code Online (Sandbox Code Playgroud)

以上是open在Modern Perl 中使用的基本示例(即三个arg open,lexical filehandles,autodie和say/print最佳实践).

但是,实际上没有必要使用$new$append词法变量(包含文件句柄)来污染命名空间.所以对于第1-3点,我可能会觉得更开心:

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

{ 
    open my $fh, '>>', 'fileio.txt';
    say {$fh} 'world';
}
Run Code Online (Sandbox Code Playgroud)

要么:

use IO::File;   # core module

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


更新:澄清:写完第一行后不需要重新打开文本文件

并且没有提及是否需要重新打开文件以读取第二行,因此它可以像这样完成:

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;
Run Code Online (Sandbox Code Playgroud)

/ I3az /


Ion*_*tan 5

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)
Run Code Online (Sandbox Code Playgroud)

  • 实际上,它是Io,大写的是i,而不是Lo.:) (8认同)
  • 诗意的讽刺! (4认同)
  • @strager:正确. (2认同)
  • @otz,无法区分♯和#. (2认同)

Hel*_*len 5

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);
Run Code Online (Sandbox Code Playgroud)

  • @ st0le:是的; 我更喜欢JScript. (3认同)
  • VBScript版本并非如此不同...... (2认同)

Mit*_*ski 5

帕斯卡尔

 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.
Run Code Online (Sandbox Code Playgroud)

  • 美丽:)我不知道为什么,但我喜欢这种语法.也许是因为它让我想起高中:) (3认同)

OTZ*_*OTZ 5

蟒蛇

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(),
Run Code Online (Sandbox Code Playgroud)


Ber*_*ron 5

Ĵ

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

最后一行读取文件(1!:1 < f),将其剪切为行(< ;. _2),获取第二个元素(1 {).然后;Monadic用于拆除元素.