这必须是所有程序员不时有的常见问题。 如何从文本文件中读取一行?然后下一个问题是我如何写回来。
当然,大多数人在日常编程中使用高级框架(可以在答案中使用),但有时也很高兴知道如何在较低级别进行编程。
我自己知道如何在C
,C++
和Objective-C
中执行此操作,但如果只是为了查看它是如何在所有流行语言中完成的话,这肯定会很方便帮助我们更好地决定使用什么语言来处理我们的文件。特别是我认为看看如何在字符串操作语言中完成它会很有趣,例如:python
,ruby
和当然perl
。
所以我在这里可以创建 社区资源 ,我们可以 明星 添加到我们的个人资料中请参阅我们何时需要以某种新语言执行文件I / O 。更不用说曝光我们都会得到我们日常不处理的语言。
您需要回答以下问题:
澄清:
对语言没有特别限制。
C
,C++
,C#
,Java
,Objective-C
都很棒。
如果您知道如何在Prolog
,Haskell
,Fortran
,Lisp
或Basic
中执行该操作,请立即前进。
答案 0 :(得分:242)
The specs至少可以说是粗略的,但我尽我所能。让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
答案 1 :(得分:48)
with open('fileio.txt', 'w') as f:
f.write('hello')
with open('fileio.txt', 'a') as f:
f.write('\nworld')
with open('fileio.txt') as f:
s = f.readlines()[1]
print(s)
<强>澄清强>
readlines()返回文件中所有行的list条。 因此,readlines()的调用导致读取文件的每一行。 在那种特殊情况下,使用readlines()是很好的,因为我们必须要读取整个文件(我们想要它的最后一行)。 但是如果我们的文件包含很多行而我们只想打印它的第n行,则不必读取整个文件。 以下是在Python中获取文件第n行的更好方法:What substitutes xreadlines() in Python 3?。
这是什么声明? with语句启动一个代码块,您可以在其中使用变量f作为从open()调用返回的stream object。 当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 :(得分:43)
,------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-],------------------------------------------------>,------------------------------------------------>,------------------------------------------------>[-]+++++++++>[-]+++++++++>[-]+++++++++<<<<<[>>>>>>+>>>+<<<<<<<<<-]>>>>>>>>>[<<<<<<<<<+>>>>>>>>>-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<<->>>->>>>>[-]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<[>>>>+>+<<<<<-]>>>>>[<<<<<+>>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<<->>>->>>>[-]<<<<<<<[>>>>>+>>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>][-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<[-]+<[-]+<<<<<<[>>>>>>[-]<<<<<<[-]]>>>>>>[[-]+<<<<<[>>>>>[-]<<<<<[-]]>>>>>[[-]+<<<<[>>>>[-]<<<<[-]]>>>>[[-]+<<<[>>>[-]<<<[-]]>>>[[-]+<<[>>[-]<<[-]]>>[[-]+<[>[-]<[-]]>[[-]+++++++++++++++++++++++++++++++++++++++++++++++++.-...>[-]<[-]]<>[-]]<<>>[-]]<<<>>>[-]]<<<<>>>>[-]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]]<<<<<>>>>>[-]]<<<<<<>>>>>>>[<<<<<<<<[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]>[-]++++++++++<<+<<<<<<+>>>>>>>>>>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<->>->>>[-]<<<<<[>>>+>>+<<<<<-]>>>>>[<<<<<+>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<[>[-]<[-]]>[[-]+>[<[-]>[-]]<[<<<<<<<[-]<+>>>>>>>>[-]]><[-]]<<<<<<<<[>>>>>>+>>+<<<<<<<<-]>>>>>>>>[<<<<<<<<+>>>>>>>>-]>[-]++++++++++>>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>[<<<<<<->>>->>>[-]<<<<<<[>>>>+>>+<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]<<<[>>+>+<<<-]>>>[<<<+>>>-][-]<<[>>[-]<[>[-]+<[-]]<[-]]>[-]>]<<<<[-]+<<[>>[-]<<[-]]>>[[-]+>[<[-]>[-]]<[<<<<<<<<[-]<+>>>>>>>>>[-]]><[-]]<<<<<<<<<++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++.>>>>>>>>[-]]
答案 3 :(得分:42)
因为没有其他人做过......
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.
答案 4 :(得分: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
如果您只想读/写文件:
main :: IO ()
main = readFile "somefile.txt" >>= writeFile "someotherfile.txt"
答案 5 :(得分:35)
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);
}
答案 6 :(得分: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
答案 7 :(得分:33)
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]
,它将整个文件解析为数组。
答案 8 :(得分:29)
#!/bin/sh
echo "hello" > fileio.txt
echo "world" >> fileio.txt
LINE=`sed -ne2p fileio.txt`
echo $LINE
实际上sed -n "2p"
部分打印第二行,但问题要求第二行存储在变量中然后打印,所以......:)
答案 9 :(得分: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;
}
答案 10 :(得分:27)
我在7年内没有触及asm,所以我不得不使用谷歌一起破解这个,但仍然,它有效;)我知道它不是100%正确,但嘿:D
好的,它不起作用。抱歉,这个。虽然它最后会打印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
答案 11 :(得分:21)
(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))))
答案 12 :(得分:21)
首先,有很多嵌套回调。
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 :(得分:18)
这是一个只使用内置命令的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脚本时,建议尽可能使用内置函数,因为生成一个单独的进程可能会很慢;通过在我的机器上进行快速测试,sed
解决方案比使用read
慢约20倍。如果你要打电话给sed
一次,就像在这种情况下一样,它并不重要,因为它会比你注意到的更快地执行,但如果你要执行数百或数千有时,它可以加起来。
对于那些不熟悉语法的人,{
和}
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
答案 14 :(得分:18)
sc fileio.txt 'hello'
ac fileio.txt 'world'
$line = (gc fileio.txt)[1]
$line
答案 15 :(得分:18)
(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 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))
答案 16 :(得分:17)
let path = "fileio.txt"
File.WriteAllText(path, "hello")
File.AppendAllText(path, "\nworld")
let secondLine = File.ReadLines path |> Seq.nth 1
printfn "%s" secondLine
答案 17 :(得分:16)
近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$
答案 18 :(得分: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];
答案 19 :(得分:16)
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 :(得分:15)
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());
}
}
}
答案 21 :(得分:15)
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)
<?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 :(得分:14)
#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;
}
答案 24 :(得分: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)
}
答案 25 :(得分:12)
尽管有些人说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]至少我不会把它称为操作系统;替代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"))
答案 26 :(得分: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).
答案 27 :(得分:11)
@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(换行符)世界。所以它只是跳过第一行,只回过第二行。
<强>更新日志强>
答案 28 :(得分: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)
使用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 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)
答案 29 :(得分:11)
new File("fileio.txt").with {
write "hello\n"
append "world\n"
println secondLine = readLines()[1]
}
答案 30 :(得分:10)
Rebol []
write/lines %fileio.txt "hello"
write/lines/append %fileio.txt "world"
print last read/lines %fileio.txt
答案 31 :(得分:9)
有关如何在许多语言中执行此类操作的示例(61!),请尝试Rosetta Code上的文件I / O页面。公平地说,它似乎并没有准确地回答你所要求的 - 它正在处理整个文件I / O--但是它非常接近并且覆盖范围更广,否则这个问题可能会作为答案吸引。
答案 32 :(得分:9)
Delphi,标准的低级方式(即没有TStringList
和其他玩具):
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
f: Text;
fn: string;
ln: string;
begin
fn := ExtractFilePath(ParamStr(0)) + 'fileio.txt';
// Create a new file
FileMode := fmOpenWrite;
AssignFile(f, fn);
try
Rewrite(f);
Writeln(f, 'hello');
Writeln(f, 'world');
finally
CloseFile(f);
end;
// Read from the file
FileMode := fmOpenRead;
AssignFile(f, fn);
try
Reset(f);
Readln(f, ln);
Readln(f, ln);
Writeln(ln);
finally
CloseFile(f);
end;
end.
因为Delphi是本机Win32编译器,所以您也可以使用Windows API来处理所有I / O操作:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils, Windows;
var
f: HFILE;
fn: string;
lns: AnsiString;
fsize, amt, i: cardinal;
AfterLine1: boolean;
const
data = AnsiString('hello'#13#10'world');
begin
fn := ExtractFilePath(ParamStr(0)) + 'fileio.txt';
f := CreateFile(PChar(fn), GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
try
WriteFile(f, data, length(data), amt, nil);
finally
CloseHandle(f);
end;
f := CreateFile(PChar(fn), GENERIC_READ, 0, nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
try
fsize := GetFileSize(f, nil);
SetLength(lns, fsize);
ReadFile(f, lns[1], fsize, amt, nil);
for i := 1 to fsize do
case lns[i] of
#10: AfterLine1 := true;
else
if AfterLine1 then
Write(lns[i]);
end;
finally
CloseHandle(f);
end;
end.
而且,为了完整起见,我包括了高级方法,即使我自己从不使用它:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes;
var
fn: string;
begin
fn := ExtractFilePath(ParamStr(0)) + 'fileio.txt';
with TStringList.Create do
try
Add('hello');
Add('world');
SaveToFile(fn);
finally
Free;
end;
with TStringList.Create do
try
LoadFromFile(fn);
Writeln(Strings[1]);
finally
Free;
end;
end.
答案 33 :(得分:8)
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.
编辑:这是一个带有小辅助功能的替代解决方案,可以避免显式关闭文件。
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.
答案 34 :(得分: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]).
答案 35 :(得分:8)
有关更多信息(以及下载最新版本):
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
答案 36 :(得分:8)
使用Adobe AIR库:
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
public class fileio
{
public static function doFileIO():void
{
var file:File = File.applicationStorageDirectory.resolvePath("fileio.txt");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeUTFBytes("hello");
stream.writeUTFBytes("\nworld");
stream.close();
stream.open(file, FileMode.READ);
var content:String = stream.readUTFBytes(stream.bytesAvailable);
stream.close();
var input:String = content.split("\n")[1];
trace(input);
}
}
由于安全原因,AIR应用程序无法写入其目录,因此它使用应用程序存储目录。
答案 37 :(得分:7)
#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;
}
答案 38 :(得分:7)
#!/bin/bash
echo 'hello' > fileio.txt
echo 'world' >> fileio.txt
myvar=`tail -n 1 fileio.txt`
echo $myvar
答案 39 :(得分:7)
io.open( 'TestIO.txt', 'w' ):write( 'hello' ):write( '\n', 'world' ):close()
aLine = io.open( 'TestIO.txt', 'r' ):read( '*a' ):match( '%C*%c*(.*)' )
print( aLine )
答案 40 :(得分:7)
set f [open fileio.txt w+]
puts $f hello
puts $f world
seek $f 0
puts [lindex [split [read $f] \n] 1]
close $f
答案 41 :(得分:7)
Io
File with("fileio.txt") open write("hello\n") write("world\n") \
rewind readLines second println
这是最短的解决方案吗?
答案 42 :(得分: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
答案 43 :(得分:6)
之前已经提供了一个很好的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);
}
}
}
答案 44 :(得分:6)
import tango.text.Util, tango.io.Stdout, tango.io.device.File;
void main()
{
scope file = new File ("fileio.txt", File.ReadWriteCreate);
file.write ("hello\n");
file.write ("world\n");
auto line = splitLines (file.rewind.text())[1];
stdout(line).nl;
}
简明版:
void main()
{
with (new File ("fileio.txt", File.ReadWriteCreate))
stdout (lineOf (put("hello\n").put("world\n").rewind.text(), 1)).nl;
}
答案 45 :(得分:6)
由于与磁盘空间和内存使用情况相关的历史原因。 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
答案 46 :(得分:6)
示例1:
with open('fileio.txt', 'a') as f:
f.write('hello')
f.write('\nworld')
with open('fileio.txt') as f:
s = f.readlines()[1]
print s
示例2 - 没有上下文管理器:
f = open('fileio.txt', 'a')
f.write('hello')
f.write('\nworld')
f.close()
f = open('fileio.txt')
s = f.readlines()[1]
f.close()
print s
答案 47 :(得分:6)
我最近一直在讨厌FORTRAN,所以这里有:
PROGRAM FILEIO
C WRITES TWO LINES TO A TEXT FILE AND THEN RETRIEVES THE SECOND OF
C THEM
CHARACTER*5 STRIN
OPEN(UNIT=1, FILE='FILEIO.TXT')
WRITE(1,100) 'HELLO'
WRITE (1,100) 'WORLD'
CLOSE(1)
C
OPEN(UNIT=2, FILE='FILEIO.TXT')
READ(2,100) STRIN
READ(2,100) STRIN
WRITE(*,*) STRIN
100 FORMAT(A5)
STOP
END
由ldigas编辑:另一方面,我喜欢它 (很抱歉弄乱你的答案;我不想开始另一个Fortran帖子)
character(10) :: line
open(1,file='fileio.txt',status='replace')
write(1,'("hello"/"world")'); rewind(1);
read(1,'(/a)')line; write(*,'(a)')line
end
(这是一个较新的Fortran变种......只有15-20岁左右; - )
答案 48 :(得分:6)
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!
上面是在Modern Perl中使用open
的基本示例(即三个arg open,lexical文件句柄,autodie和say / print最佳实践)。
然而,实际上没有必要用$new
和$append
词法变量(保存文件句柄)来污染命名空间。因此,对于第1-3点,我可能会感到更开心:
{
open my $fh, '>', 'fileio.txt';
say {$fh} 'hello';
}
{
open my $fh, '>>', 'fileio.txt';
say {$fh} 'world';
}
或:
use IO::File; # core module
IO::File->new( 'fileio.txt', 'w' )->print( "hello\n" );
IO::File->new( 'fileio.txt', 'a' )->print( "world\n" );
更新 re:澄清:编写第一行后无需重新打开文本文件
并且没有提及是否需要重新打开文件以回读第二行,因此它可以像这样完成:
my $line = do {
open my $fh, '+>', 'fileio.txt';
say {$fh} $_ for qw/hello world/; # or just: say {$fh} "hello\nworld" :)
seek $fh, 0, 0; # rewind to top of file
(<$fh>)[1]; # no need to be lazy with just 2 recs!
};
print $line;
/ I3az /
答案 49 :(得分:5)
f =: 'fileio.txt'
('hello', LF) 1!:2 < f
('world', LF) 1!:3 < f
; 1 { < ;. _2 (1!:1 < f)
最后一行读取文件(1!:1 < f
),将其剪切为行(< ;. _2
),获取第二个元素(1 {
)。然后Monadic ;
用于取消元素的包装。
答案 50 :(得分: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)
答案 51 :(得分:5)
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);
答案 52 :(得分: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.
答案 53 :(得分: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(),
答案 54 :(得分:4)
Ioke
path = "fileio.txt"
FileSystem withOpenFile(path, fn(f,
f println("hello"))
)
FileSystem withOpenFile(path, fn(f,
f println("world"))
)
FileSystem readLines(path) [1] print
答案 55 :(得分:4)
f:`fileio.txt
f 0:/:(*a;a:$`hello`world)
`0:*1_0:f
答案 56 :(得分:4)
var FS = require("narwhal/fs");
FS.open("fileio.txt", "w")
.print("hello")
.print("world")
.close()
var stream = FS.open("fileio.txt", "r");
stream.next();
print(stream.next());
stream.close();
这是另一个特殊的JavaScript嵌入。
答案 57 :(得分:4)
因为你想逐行阅读,你不能使用slurp,所以
(use 'clojure.java.io)
然后是传统的lisp风格:
(let [f "hello.txt"]
(spit f "hello\n")
(spit f "world\n" :append true)
(print (second (line-seq (reader f)))))
或,丧失了心爱的括号:
(doto "hello.txt"
(spit "hello\n")
(spit "world\n" :append true)
(-> reader line-seq second print ))
答案 58 :(得分:4)
#lang racket
(call-with-output-file "fileio.txt"
#:exists 'truncate
(lambda (out)
(fprintf out "hello\n" )))
(call-with-output-file "fileio.txt"
#:exists 'append
(lambda (out)
(fprintf out "world\n" )))
(call-with-input-file "fileio.txt"
(lambda (in)
(read-line in)
(display (read-line in))))
答案 59 :(得分:4)
(没有命令行反馈)
BEGIN {
print "hello" > "fileio.txt"
print "world" > "fileio.txt"
for ( i = 0; i < 2; i ++ )
getline < "fileio.txt"
fflush( "fileio.txt" );
print $0
}
答案 60 :(得分:3)
(Creatures 3游戏引擎的脚本语言)
* Open fileio.txt for output (non-append) in global directory
FILE OOPE 0 "fileio.txt" 0
OUTS "hello\n"
OUTS "world\n"
* Close file
FILE OCLO
* Open file for read
FILE IOPE 0 "fileio.txt"
SETS VA00 INNL * read line
SETS VA00 INNL * read line
DBG: OUTS VA00 * print to debug console
FILE ICLO
答案 61 :(得分:3)
<强> ColdFusion的强>
创建一个名为“fileio.txt”的新文本文件 将第一行“hello”写入文本文件。
<cffile action="Write" file="fileio.txt" output="hello">
将第二行“world”附加到文本文件中。
<cffile action="Append" file="fileio.txt" output="world">
将第二行“world”读入输入字符串。 将输入字符串打印到控制台。
<cffile action="read" file="fileio.txt" variable="filecontents">
<cfoutput>#ListLast(filecontents,Chr(13) & Chr(10))#</cfoutput>
答案 62 :(得分:3)
原始提交:
(w/stdout (outfile "fileio.txt")
prn!hello
prn!world)
(pr:cadr:readfile "fileio.txt")
有人指出,这不符合附加第二行的要求(而不是连续写入)。 waterhouse更正了此问题,并在其版本中进行了其他改进:
(w/outfile f "fileio.txt"
(disp "hello\n" f))
(w/appendfile f "fileio.txt"
(disp "world\n" f))
(pr:cadr:readfile "fileio.txt")
更新:此最终版本解决了可能没有将“世界”读入变量的问题:
(w/outfile f "fileio.txt"
(disp "hello\n" f))
(w/appendfile f "fileio.txt"
(disp "world\n" f))
(w/infile f "fileio.txt"
(repeat 2 (= l readline.f))
(prn l))
答案 63 :(得分:3)
import System.IO
path = "fileio.txt"
File.WriteAllText(path, "hello")
File.AppendAllText(path, "\nworld")
secondLine = File.ReadAllLines(path)[1]
print secondLine
答案 64 :(得分:3)
<强> MATLAB 强>
使用低级例程fopen / fclose / fseek / fscanf / etc
% read a integers from a file...
file = fopen('filename', 'r'); // read only
if (file == -1)
error('file can''t be read');
end
[number, count] = fscanf(file, '%d', 1);
while (count == 1)
fprintf('read %d\n', number);
[number, count] = fscanf(file, '%d', 1);
end
fclose(file);
使用高级例程load / save / textscan / uigetfile / etc
% Load and store a matrix
M = load('sample_file.txt')
save filename M
答案 65 :(得分:3)
with open('fileio.txt','w') as f:
print>>f,'hello' #write
print>>f,'world'
with open('afile.txt','r') as f:
s = f.readlines()[1] #read
print s
答案 66 :(得分:3)
MUMPS
FILEIO ;
N F,L1,L2
S F="FILEIO.TXT"
O F:"WNS" U F W "hello" C F
O F:"WAS" U F W !,"world" C F
O F:"RS" U F R L1,L2 C F W L2,!
Q
答案 67 :(得分:2)
BEGIN {
print "hello" > "fileio.txt"
print "world" > "fileio.txt" # subsequent writes to the same output file append to it
close("fileio.txt")
}
/world/ { print $0 }
执行脚本
$ awk -f script.awk fileio.txt
答案 68 :(得分:2)
改编自海伦对JScript的回答。
fileName = "fileio.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.CreateTextFile(fileName, true)
file.WriteLine("hello")
file.WriteLine("world")
file.Close()
ForReading = 1
Set file = fso.OpenTextFile(fileName, ForReading,false)
file.SkipLine()
WScript.Echo(file.ReadLine())
'Msgbox(file.ReadLine()) 'same as above
file.Close()
答案 69 :(得分:2)
UniVerse BASIC / UniData UniBASIC
* UFD is the 'User File Directory' in this account
* This may be called &UFD& in UniVerse
OPEN 'UFD' TO F.UFD ELSE
CRT 'CANNOT OPEN UFD'
STOP
END
* Write to file
REC = ''
REC<1> = 'Hello'
REC<2> = 'World'
* When writing to a filesystem, each attribute of a dynamic array is stored
* as a separate line in the file. When writing to a hashed file (aka, table)
* each attribute is stored separated by a field mark.
WRITE REC TO F.UFD,'fileio.txt'
* Read from file
REC = ''
READ REC FROM F.UFD,'fileio.txt' ELSE
CRT 'CANNOT READ RECORD'
STOP
END
CRT REC<2>
还有其他方法可以做到这一点,例如使用顺序文件(OPENSEQ / READSEQ / WRITESEQ / CLOSESEQ)。这是一种简单的方法,因为它像任何其他记录一样处理文件。
答案 70 :(得分:2)
经典ASP / VBScript
我知道这很快就会消失,但是,嗯!
您可以使用create
中的可选openTextFile
参数创建一个不存在的文本文件,但我已经很长时间地展示了它。
这是未经测试但应该可以正常工作。
<%
Option Explicit
Dim objFso
Dim ourFile
Dim strFilePath
Dim strLine
strFilePath = Map("fileIO.txt")
Set objFso = CreateObject("Scripting.FileSystemObject")
'Create text file, add hello line
Set ourFile = objFso.CreateTextFile(strFilePath)
ourFile.WriteLine("hello")
ourFile.close
'Append world to a newline
Set ourFile = objFso.OpenTextFile(strFilePath, ForWriting)
ourFile.writeline("world")
ourFile.close
'Read lines
Set ourFile = objFso.OpenTextFile(strFilePath, ForReading)
ourFile.skipLine
strLine = ourFile.readLine
ourFile.close
'Print value
response.write(strLine)
'Clean up this shiz
Set ourFile = nothing
Set objFso = nothing
%>
答案 71 :(得分:2)
DEFINE VARIABLE cString AS CHARACTER NO-UNDO.
OUTPUT TO VALUE("fileio.txt").
PUT UNFORMATTED "hello" SKIP.
OUTPUT CLOSE.
OUTPUT TO VALUE("fileio.txt") APPEND.
PUT UNFORMATTED "world" SKIP.
OUTPUT CLOSE.
INPUT FROM VALUE("fileio.txt").
/* Read each line in to cString; at the end of the loop */
/* the variable will contain the last line of the file. */
REPEAT:
IMPORT UNFORMATTED cString.
END.
INPUT CLOSE.
MESSAGE cString.
答案 72 :(得分:2)
这与其他版本的不同之处在于,print
用于所有输出,只打开文件一次。
with open('fileio.txt', 'w+') as f:
print('hello', file=f)
pos = f.tell()
print('world', file=f)
f.seek(pos)
s = f.read()
print(s)
答案 73 :(得分:2)
path = "c:\fileio.txt"
File.WriteLine(path, 1, "Hello") 'write the first line
File.WriteLine(path, 2, "World") 'write the second line
stuff = File.ReadLine(path, 2) 'read the second line
TextWindow.WriteLine(stuff)
答案 74 :(得分:2)
procedure main(args)
f:=open("fileio.txt","w")
write(f,"hello")
close(f)
f:=open("fileio.txt","a")
write(f,"world")
close(f)
f:=open("fileio.txt","r")
line:=(!f & !f)
# or you can use
# every 1 to 2 do line:=!f
close(f)
write(line)
end
答案 75 :(得分:1)
// Disclaimer: I did this mostly because it sounded like a fun quick
// hack, I don't normally use Go at all.
// Using log.Exit like this is probably horrible style.
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func OpenFile(mode int) *os.File {
f, err := os.Open("fileio.txt", mode, 0644)
if err != nil {
log.Exit(err)
}
return f
}
// Create an interface just for fun, since it'll be satisfied
// automatically by bufio's Reader.
type HasReadString interface {
ReadString(b byte) (string, os.Error)
}
func ReadLine(r HasReadString) string {
l, err := r.ReadString('\n')
if err != nil {
log.Exit(err)
}
return l
}
func main() {
f := OpenFile(os.O_CREAT | os.O_TRUNC | os.O_WRONLY)
defer f.Close()
f.WriteString("hello\n")
f.WriteString("world\n")
f = OpenFile(os.O_RDONLY)
defer f.Close()
r := bufio.NewReader(f)
_ = ReadLine(r)
fmt.Print(ReadLine(r))
}
答案 76 :(得分:1)
Java Me
public static void writeFile(String fileName, String data) {
FileConnection fconn = null;
OutputStream os = null;
try {
String fName = "file:///SDCard/" + fileName;
fconn = (FileConnection) Connector
.open(fName, Connector.READ_WRITE);
if (!fconn.exists()) {
fconn.create();
}
//for append use following line
//os = fconn.openOutputStream(fconn.fileSize());
os = fconn.openOutputStream();
os.write(data.getBytes());
} catch (Exception e) {
System.out.println("Output file error: " + e.getMessage());
} finally {
try {
os.close();
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
private static byte[] readFile(String fileName) {
String fName = "file:///SDCard/" + fileName;
byte[] data = null;
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector.open(fName, Connector.READ);
is = fconn.openDataInputStream();
byte b[] = new byte[1024];
int length = is.read(b, 0, 1024);
System.out.println("Content of "+fileName + ": "+ new String(b, 0, length));
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (null != is)
is.close();
if (null != fconn)
fconn.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return data;
}
答案 77 :(得分:1)
data;
file 'c:\fileio.txt';
put 'hello' / 'world';
data;
infile 'c:\fileio.txt';
input /;
put _infile_;
答案 78 :(得分:0)
原始帖子的链接运行列表对于Arc有几个错误。这是更正后的版本:
<a href="http://arclanguage.org">Arc</a> -
<a href="http://stackoverflow.com/questions/3538156/file-i-o-in-every-programming-language/3539940#3539940">evanrmurphy</a>
(很抱歉为此更正添加了一个全新的答案,但我没有足够的声誉来发表评论。一旦修复,请随意删除。谢谢。)
答案 79 :(得分:-7)