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

发布于 2024-09-15 01:10:27 字数 1130 浏览 5 评论 0 原文

这想必是所有程序员时不时都会遇到的一个常见问题。 如何从文本文件中读取一行?那么下一个问题总是我如何写回来。

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

我自己知道如何在 CC++Objective-C 中执行此操作,但了解它是如何在所有代码中完成的肯定会很方便流行语言中的一些,只是为了帮助我们更好地决定使用哪种语言进行文件 io。特别是我认为看看它在字符串操作语言中是如何完成的会很有趣,例如: python< /code>、ruby,当然还有 perl

因此,我认为我们可以在这里创建一个社区资源,我们都可以为我们的个人资料添加星标,并在何时进行参考我们需要用某种新语言进行文件 I/O。更不用说我们都会接触到我们日常不接触的语言。

您需要这样回答:

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

说明:

  • 您应该仅针对每个答案展示如何使用一种编程语言来执行此操作。
  • 假设文本文件事先不存在
  • 写入第一行后不需要重新打开文本文件

对语言没有特殊限制。 CC++C#JavaObjective-C 都很棒。

如果您知道如何使用 PrologHaskellFortranLispBasic< /code> 那么请继续。

This has to be a common question that all programmers have from time to time.
How do I read a line from a text file? Then the next question is always how do i write it back.

Of course most of you use a high level framework in day to day programming (which are fine to use in answers) but sometimes it's nice to know how to do it at a low level too.

I myself know how to do it in C, C++ and Objective-C, but it sure would be handy to see how it's done in all of the popular languages, if only to help us make a better decision about what language to do our file io in. In particular I think it would be interesting to see how its done in the string manipulation languages, like: python, ruby and of course perl.

So I figure here we can create a community resource that we can all star to our profiles and refer to when we need to do file I/O in some new language. Not to mention the exposure we will all get to languages that we don't deal with on a day to day basis.

This is how you need to answer:

  1. Create a new text file called "fileio.txt"
  2. Write the first line "hello" to the text file.
  3. Append the second line "world" to the text file.
  4. Read the second line "world" into an input string.
  5. Print the input string to the console.

Clarification:

  • You should show how to do this in one programming language per answer only.
  • Assume that the text file doesn't exist beforehand
  • You don't need to reopen the text file after writing the first line

No particular limit on the language.
C, C++, C#, Java, Objective-C are all great.

If you know how to do it in Prolog, Haskell, Fortran, Lisp, or Basic then please go right ahead.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

此刻的回忆 2024-09-22 01:11:29

格罗维

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

Groovy

new File("fileio.txt").with { 
    write  "hello\n"
    append "world\n"   
    println secondLine = readLines()[1]
}
撑一把青伞 2024-09-22 01:11:27

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 库

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)

Scala:

Using standard library:

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)

Using Josh Suereth's 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)      


Since many people have used the same file descriptor to write the two strings, I'm also including that way in my answer.

Using standard library:

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)

Using Josh Suereth's 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)
无边思念无边月 2024-09-22 01:11:26

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(换行符)world。所以它只是跳过第一行并仅回显第二行。

变更日志

  • 2 - 哦,一定是误读了需求,或者他们对我进行了更改。现在从文件中读取最后一行

Windows Batch Files - Version #2

@echo off
echo hello > fileio.txt
echo world  >> fileio.txt
set /P answer=Insert: 
echo %answer%  >> fileio.txt
for /f "skip=1 tokens=*" %%A in (fileio.txt) do echo %%A

To explain that last horrible looking for loop, it assumes that there is only hello (newline) world in the file. So it just skips the first line and echos only the second.

Changelog

  • 2 - Opps, must of misread the requirements or they changed on me. Now reads last line from file

七七 2024-09-22 01:11:25

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

[1] 至少我不会称其为操作系统;一个替代的用户界面是的,一个操作系统不是。

[2] 您可以仅加载文件的部分内容,但这只能按字节指定。

[3] 缓冲区既是一种类似于字符串的数据类型,也是“编辑文件时看到的东西”。虽然编辑缓冲区显示在窗口中,但缓冲区不一定对用户可见。

编辑:如果您想看到插入到缓冲区中的文本,显然必须使其可见,并在操作之间休眠。因为 Emacs 通常只在等待用户输入时重新显示屏幕(睡眠与等待输入不同),所以您还必须强制重新显示。这在本例中是必要的(用它代替第二个 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"))

Emacs Lisp

Despite what some people say Emacs is mainly a text editor [1]. So while Emacs Lisp can be used to solve all kinds of problems it is optimized towards the needs of a text editor. Since text editors (obviously) have quite specific needs when it comes to how files are handled this affects what file related functionality Emacs Lisp offers.

Basically this means that Emacs Lisp does not offer functions to open a file as a stream, and read it part by part. Likewise you can't append to a file without loading the whole file first. Instead the file is completely [2] read into a buffer [3], edited and then saved to a file again.

For must tasks you would use Emacs Lisp for this is suitable and if you want to do something that does not involve editing the same functions can be used.

If you want to append to a file over and over again this comes with a huge overhead, but it is possible as demonstrated here. In practice you normally finish making changes to a buffer whether manually or programmatically before writing to a file (just combine the first two s-expressions in the example below).

(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] At least I would not go as far as calling it an OS; an alternative UI yes, an OS no.

[2] You can load only parts of a file, but this can only be specified byte-wise.

[3] A buffer is both a datatype in someways similar to a string as well as the "thing you see while editing a file". While editing a buffer is displayed in a window but buffers do not necessarily have to be visible to the user.

Edit: If you want to see the text being inserted into the buffer you obviously have to make it visible, and sleep between actions. Because Emacs normally only redisplays the screen when waiting for user input (and sleeping ain't the same as waiting for input) you also have to force redisplay. This is necessary in this example (use it in place of the second sexp); in practice I never had to use `redisplay' even once - so yes, this is ugly but ...

(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"))
凝望流年 2024-09-22 01:11:24

Erlang

可能不是最惯用的 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).

Erlang

Probably not the most idiomatic Erlang, but:

#!/usr/bin/env escript

main(_Args) ->
  Filename = "fileio.txt",
  ok = file:write_file(Filename, "hello\n", [write]),
  ok = file:write_file(Filename, "world\n", [append]),
  {ok, File} = file:open(Filename, [read]),
  {ok, _FirstLine} = file:read_line(File),
  {ok, SecondLine} = file:read_line(File),
  ok = file:close(File),
  io:format(SecondLine).
捎一片雪花 2024-09-22 01:11:23

开始

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

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)
}
流殇 2024-09-22 01:11:22

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

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

or somewhat less pedantically,

#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;
}
爺獨霸怡葒院 2024-09-22 01:11:20

爪哇

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

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());
    }       
  }
}
望喜 2024-09-22 01:11:19

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

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
雄赳赳气昂昂 2024-09-22 01:11:17

回复:

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

R:

cat("hello\n", file="fileio.txt")
cat("world\n", file="fileio.txt", append=TRUE)
line2 = readLines("fileio.txt", n=2)[2]
cat(line2)
千紇 2024-09-22 01:11:16

珀尔

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

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];
草莓味的萝莉 2024-09-22 01:11:15

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

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]);
怎会甘心 2024-09-22 01:11:14

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$

BASIC

I haven't used BASIC in almost 10 years, but this question gave me a reason to quickly brush up my knowledge. :)

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$
孤独岁月 2024-09-22 01:11:13

F#

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

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

F#

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

let secondLine = File.ReadLines path |> Seq.nth 1
printfn "%s" secondLine
苦妄 2024-09-22 01:11:11

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

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

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

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

Or equivalently, using the threading macro -> (also known as the 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))
云归处 2024-09-22 01:11:09

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

在编写重要的 shell 脚本时,建议尽可能使用内置脚本,因为生成单独的进程可能会很慢;根据我机器上的快速测试,sed 解决方案比使用 read 慢大约 20 倍。如果您要调用 sed 一次,就像在本例中一样,这并不重要,因为它的执行速度比您注意到的要快,但如果您要执行它数百或数千次,它可以累加。

对于那些不熟悉语法的人,{} 在当前 shell 环境中执行命令列表(与创建子 shell 的 相反;我们需要在当前 shell 环境中运行,因此我们可以稍后使用该变量的值)。我们需要将这些命令组合在一起,以便它们在同一个输入流上运行,该输入流是通过从 fileio.txt 重定向创建的;如果我们只是运行 read <文件io.txt;读取输入< fileio.txt,我们只会得到第一行,因为文件将在两个命令之间关闭并重新打开。由于 shell 语法的特殊性({} 是保留字,而不是元字符),我们需要将 { 和 < code>} 从其余命令中以空格分隔,并以 ; 终止命令列表。

read 内置函数 作为参数要读入的变量的名称。它消耗一行输入,用空格分隔输入(从技术上讲,它根据 $IFS 的内容来分隔它,默认为空格字符,其中空格字符意味着将其拆分为任何空格、制表符或换行符),将每个单词分配给按顺序给出的变量名称,并将该行的其余部分分配给最后一个变量。由于我们只提供一个变量,因此它只是将整行放入该变量中。我们重用 $input 变量,因为我们不关心第一行的内容(如果我们使用 Bash,我们可以不提供变量名,但为了可移植,您必须始终提供至少一个名字)。

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

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

Shell Script

Here's a shell script using just builtin commands, rather than invoking external commands such as sed or tail as previous responses have done.

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

When writing significant shell scripts, it is advisable to use builtins as much as possible, since spawning a separate process can be slow; from a quick test on my machine, the sed solution is about 20 times slower than using read. If you're going to call sed once, as in this case, it doesn't really matter much, as it will execute more quickly than you can notice, but if you're going to execute it hundreds or thousands of times, it can add up.

For those unfamiliar with the syntax, { and } execute a list of commands in the current shell environment (as opposed to ( and ) which create a subshell; we need to be operating in the current shell environment, so we can use the value of the variable later). We need to group the commands together in order to have them both operate on the same input stream, created by redirecting from fileio.txt; if we simply ran read < fileio.txt; read input < fileio.txt, we would just get the first line, as the file would be closed and re-opened between the two commands. Due to an idiosyncrasy of shell syntax ({ and } are reserved words, as opposed to metacharacters), we need to separate the { and } from the rest of the commands with spaces, and terminate the list of commands with a ;.

The read builtin takes as an argument the names of variables to read into. It consumes a line of input, breaks the input by whitespace (technically, it breaks it according to the contents of $IFS, which defaults to a space character, where a space character means split it on any of space, tab, or newline), assigns each word to the variable names given in order, and assigns the remainder of the line to the last variable. Since we're just supplying one variable, it just puts the whole line in that variable. We reuse the $input variable, since we don't care what's on the first line (if we're using Bash we could just not supply a variable name, but to be portable, you must always supply at least one name).

Note that while you can read lines one at a time, like I do here, a much more common pattern would be to wrap it in a while loop:

while read foo bar baz
do
  process $foo $bar $baz
done < input.txt
灵芸 2024-09-22 01:11:06

电源外壳

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

PowerShell

sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line
我很OK 2024-09-22 01:11:05

通用语言

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

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))))
半窗疏影 2024-09-22 01:11:02

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

JavaScript - node.js

First, lots of nested callbacks.

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

A little bit cleaner:

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)));
我家小可爱 2024-09-22 01:11:00

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

x86 Assembler (NASM) on Linux

I haven't touched asm in 7 years, so I had to use google a bit to hack this together, but still, it works ;) I know it's not 100% correct, but hey :D

OK, it doesn't work. sorry bout this. while it does print world in the end, it doesn't print it from the file, but from the ecx which is set on line 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

References used:
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

请恋爱 2024-09-22 01:10:59

Shell 脚本 (UNIX)

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

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

Shell Script (UNIX)

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

Actually the sed -n "2p" part prints the second line, but the question asks for the second line to be stored in a variable and then printed, so... :)

白鸥掠海 2024-09-22 01:10:58

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

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) is .Net 4.0 only, the alternative is File.ReadAllLines(path)[1] which parses the whole file into an array.

缱倦旧时光 2024-09-22 01:10:58

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

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;
}
路弥 2024-09-22 01:10:57

红宝石

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

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
森林散布 2024-09-22 01:10:56

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

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);
}
时光无声 2024-09-22 01:10:55

Haskell

main :: IO ()
main = let filePath = "fileio.txt" in
       do writeFile filePath "hello"
          appendFile filePath "\nworld"
          fileLines <- readFile filePath
          let secondLine = (lines fileLines) !! 1
          putStrLn secondLine

如果你只想读/写一个文件:

main :: IO ()
main = readFile "somefile.txt" >>= writeFile "someotherfile.txt" 

Haskell

main :: IO ()
main = let filePath = "fileio.txt" in
       do writeFile filePath "hello"
          appendFile filePath "\nworld"
          fileLines <- readFile filePath
          let secondLine = (lines fileLines) !! 1
          putStrLn secondLine

If you just want to read/write a file:

main :: IO ()
main = readFile "somefile.txt" >>= writeFile "someotherfile.txt" 
倒数 2024-09-22 01:10:52

大脑***k

,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<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>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<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++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]

Brain***k

,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>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]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+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+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]
掌心的温暖 2024-09-22 01:10:52

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.

COBOL

Since nobody else did......

IDENTIFICATION DIVISION.
PROGRAM-ID.  WriteDemo.
AUTHOR.  Mark Mullin.
* Hey, I don't even have a cobol compiler

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
        ORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD TestFile.
01 TestData.
   02  LineNum        PIC X.
   02  LineText       PIC X(72).

PROCEDURE DIVISION.
Begin.
    OPEN OUTPUT TestFile
    DISPLAY "This language is still around."

    PERFORM GetFileDetails
    PERFORM UNTIL TestData = SPACES
       WRITE TestData 
       PERFORM GetStudentDetails
    END-PERFORM
    CLOSE TestFile
    STOP RUN.

GetFileDetails.
    DISPLAY "Enter - Line number, some text"
    DISPLAY "NXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    ACCEPT  TestData.
ペ泪落弦音 2024-09-22 01:10:51

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() 会读取文件的每一行。
    在这种特殊情况下,使用 readlines() 就可以了,因为无论如何我们都必须读取整个文件(我们想要它的最后一行)。
    但是如果我们的文件包含很多行并且我们只想打印它的第 n 行,则没有必要读取整个文件。
    以下是一些在 Python 中获取文件第 n 行的更好方法: 什么替代 xreadlines( )在 Python 3 中?

  • 这是什么 with 语句?
    with 语句启动一个代码块,您可以在其中使用变量 f 作为 从调用 open() 返回的流对象
    当with块结束时,python自动调用f.close()。
    这保证了当您退出 with 块时文件将被关闭,无论您如何或何时退出该块
    (即使您通过未处理的异常退出它)。您可以显式调用 f.close(),但是如果您的代码引发异常并且您没有调用 f.close(),该怎么办?这就是 with 语句有用的原因。

  • 您无需在每次操作前重新打开文件。您可以将整个代码编写在一个 with 块中。

    with open('fileio.txt', 'w+') as f:
        f.write('你好')
        f.write('\n世界')
        s = f.readlines()[1]
    印刷)
    

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

Python 3

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

Clarifications

  • readlines() returns a list of all the lines in the file.
    Therefore, the invokation of readlines() results in reading each and every line of the file.
    In that particular case it's fine to use readlines() because we have to read the entire file anyway (we want its last line).
    But if our file contains many lines and we just want to print its nth line, it's unnecessary to read the entire file.
    Here are some better ways to get the nth line of a file in Python: What substitutes xreadlines() in Python 3?.

  • What is this with statement?
    The with statement starts a code block where you can use the variable f as a stream object returned from the call to open().
    When the with block ends, python calls f.close() automatically.
    This guarantees the file will be closed when you exit the with block no matter how or when you exit the block
    (even if you exit it via an unhandled exception). You could call f.close() explicitly, but what if your code raises an exception and you don't get to the f.close() call? That's why the with statement is useful.

  • You don't need to reopen the file before each operation. You can write the whole code inside one with block.

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

    I used three with blocks to emphsize the difference between the three operations:
    write (mode 'w'), append (mode 'a'), read (mode 'r', the default).

度的依靠╰つ 2024-09-22 01:10:49

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

LOLCODE

The specs are sketchy to say the least, but I did the best I could. Let the downvoting begin! :) I still find it a fun exercise.

HAI
CAN HAS STDIO?
PLZ OPEN FILE "FILEIO.TXT" ITZ "TehFilez"?
    AWSUM THX
        BTW #There is no standard way to output to files yet...
        VISIBLE "Hello" ON TehFilez
        BTW #There isn't a standard way to append to files either...
        MOAR VISIBLE "World" ON TehFilez
        GIMMEH LINES TehLinez OUTTA TehFilez
        I HAS A SecondLine ITZ 1 IN MAH TehLinez
        VISIBLE SecondLine
    O NOES
        VISIBLE "OH NOES!!!"
KTHXBYE
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文