为什么在这里不读取文件的第一行

时间:2019-05-10 13:02:01

标签: file smalltalk gnu-smalltalk

我正在尝试以下代码来读取和打印目录中所有扩展名为.st的文件的第一行:

(Directory working: '.')
allFilesMatching: '*.st' do: [ :ff |
    line := (ff nextLine).    "Read first line only."
    line displayNl.
    ff close. ]

但是,它无法正常工作并出现以下错误:

$ gst firstline3.st 
"Global garbage collection... done"
Object: nil error: did not understand #oldFileNamed:
MessageNotUnderstood(Exception)>>signal (ExcHandling.st:254)
UndefinedObject(Object)>>doesNotUnderstand: #oldFileNamed: (SysExcept.st:1448)
optimized [] in UndefinedObject>>executeStatements (firstline3.st:3)
[] in Kernel.RecursiveFileWrapper(FilePath)>>filesMatching:do: (FilePath.st:903)
[] in Kernel.RecursiveFileWrapper>>namesDo:prefixLength: (VFS.st:378)
[] in File>>namesDo: (File.st:589)
BlockClosure>>ensure: (BlkClosure.st:268)
File>>namesDo: (File.st:586)
Kernel.RecursiveFileWrapper>>namesDo:prefixLength: (VFS.st:373)
Kernel.RecursiveFileWrapper>>namesDo: (VFS.st:396)
Kernel.RecursiveFileWrapper(FilePath)>>filesMatching:do: (FilePath.st:902)
File(FilePath)>>allFilesMatching:do: (FilePath.st:775)
Directory class>>allFilesMatching:do: (Directory.st:225)
UndefinedObject>>executeStatements (firstline3.st:2)

问题出在哪里?感谢您的帮助。

编辑: @tucan的答案中的以下代码不起作用:

(Directory working: '.') allFilesMatching: '*.st' do: [ :ff |
   file := FileStream open: ff mode: FileStream read.
   file nextLine printNl.       "I want to print it right away"
   file close
].

错误是:

$ gst firstline3.st 
"Global garbage collection... done"
Object: RecursiveFileWrapper new "<0x7f6decddd780>" error: did not understand #indexOfSubCollection:
MessageNotUnderstood(Exception)>>signal (ExcHandling.st:254)
Kernel.RecursiveFileWrapper(Object)>>doesNotUnderstand: #indexOfSubCollection: (SysExcept.st:1448)
FileStream class(FileDescriptor class)>>open:mode:ifFail: (FileDescr.st:131)
FileStream class(FileDescriptor class)>>open:mode: (FileDescr.st:111)
optimized [] in UndefinedObject>>executeStatements (firstline3.st:2)
[] in Kernel.RecursiveFileWrapper(FilePath)>>filesMatching:do: (FilePath.st:903)
[] in Kernel.RecursiveFileWrapper>>namesDo:prefixLength: (VFS.st:378)
[] in File>>namesDo: (File.st:589)
BlockClosure>>ensure: (BlkClosure.st:268)
File>>namesDo: (File.st:586)
Kernel.RecursiveFileWrapper>>namesDo:prefixLength: (VFS.st:373)
Kernel.RecursiveFileWrapper>>namesDo: (VFS.st:396)
Kernel.RecursiveFileWrapper(FilePath)>>filesMatching:do: (FilePath.st:902)
File(FilePath)>>allFilesMatching:do: (FilePath.st:775)
Directory class>>allFilesMatching:do: (Directory.st:225)
UndefinedObject>>executeStatements (firstline3.st:1)

好的。解决:FileStream open: (ff name)有用。

1 个答案:

答案 0 :(得分:1)

我在打开文件的代码中看不到任何地方。您需要在代码块中执行以下操作才能打开文件

text-match