Это должен быть общий вопрос, который время от времени возникает у всех программистов. Как мне прочитать строку из текстового файла? Тогда следующий вопрос всегда - как мне написать это обратно.
Конечно, большинство из вас используют высокоуровневую инфраструктуру в повседневном программировании (которую можно использовать в ответах), но иногда приятно знать, как это делать и на низком уровне.
Я сам знаю, как сделать это в C
, C ++
и Objective-C
, но было бы удобно увидеть, как это делается на всех популярных языках, если только чтобы помочь нам принять лучшее решение о том, на каком языке делать наш файл. В частности, я думаю, что было бы интересно посмотреть, как это делается на языках манипулирования строками, например: python
, ruby
и, конечно, perl
.
Итак, я полагаю, что здесь мы можем создать ресурс сообщества , чтобы мы могли пометить звездочкой в наших профилях и сослаться на то, когда нам нужно выполнить файловый ввод / вывод на каком-то новом языке. Не говоря уже о воздействии, которое мы все получим на языки, с которыми мы не имеем дело изо дня в день.
Вот как вам нужно ответить:
Пояснение:
C
, C ++
, C #
, Java
, Objective-C
все великолепны.
Если вы знаете, как это сделать в Прологе
, Хаскеле
, Фортране
, Лиспе
или Базовом
] тогда, пожалуйста, продолжайте.
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 /textcan / uigetfile / etc
% Load and store a matrix
M = load('sample_file.txt')
save filename M
(язык сценариев для 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
Исходное сообщение:
(w/stdout (outfile "fileio.txt")
prn!hello
prn!world)
(pr:cadr:readfile "fileio.txt")
Было указано, что это не соответствовало требованиям добавления второй строки (а не непрерывного ее написания). Уотерхаус исправляет это и вносит другие уточнения в свою версию:
(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))
Адаптировано из ответа Хелен для 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()
Текущий список ссылок исходного сообщения содержит пару ошибок для 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>
(Извините, что добавляю совершенно новый ответ для этого исправления, но у меня недостаточно репутации, чтобы оставить комментарий. Не стесняйтесь удалить его, как только он будет исправлен. Спасибо.)
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)
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
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.
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
Coldfusion
Создайте новый текстовый файл с именем "fileio.txt" Напишите в текстовом файле первую строку «привет».
<cffile action="Write" file="fileio.txt" output="hello">
Добавить в текстовый файл вторую строку «мир».
<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>
data;
file 'c:\fileio.txt';
put 'hello' / 'world';
data;
infile 'c:\fileio.txt';
input /;
put _infile_;
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;
}
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). Это простой способ, поскольку он рассматривает файл как любую другую запись.
Классический 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
%>
// 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))
}
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
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
import System.IO
path = "fileio.txt"
File.WriteAllText(path, "hello")
File.AppendAllText(path, "\nworld")
secondLine = File.ReadAllLines(path)[1]
print secondLine