File io 以独立于平台的方式将行预编到文件

File io 以独立于平台的方式将行预编到文件,file-io,tcl,File Io,Tcl,在Tcl应用程序中,我需要在现有的.js文件前添加一行Javascript代码。我在谷歌上搜索了“tcl将行预处理到文件”,并没有找到任何特别有用的例子,特别是我需要它独立于平台 我发现一种有效的方法是,首先以以下方式打开文件进行读取,然后进行写入: set fileName [file join $appContentDir deleteBinDir.js] set _fileR [open $fileName r] set fileContent [read $_fileR] close $

在Tcl应用程序中,我需要在现有的.js文件前添加一行Javascript代码。我在谷歌上搜索了“tcl将行预处理到文件”,并没有找到任何特别有用的例子,特别是我需要它独立于平台

我发现一种有效的方法是,首先以以下方式打开文件进行读取,然后进行写入:

set fileName [file join $appContentDir deleteBinDir.js]
set _fileR [open $fileName r]
set fileContent [read $_fileR]
close $_fileR

set _fileW [open $fileName w]
puts $_fileW "var path = '[file join $appNwDir bin]';\n"
puts $_fileW $fileContent
close $_fileW
生成的Javascript代码为:

var path = 'C:/opt/dev/dexygen/poc/2eggz/rename_2eggz.vfs/../nw/bin'; //prepended line

var gui = require('nw.gui');
var fs = require('fs');
var p = require("path");

gui.Window.get().on('close', deleteDirectoryContents);

function deleteDirectoryContents() {
    //etc

然而,在googlesearch()的一个结果中提到需要在一个大文件前加一行,在这种情况下,我可能会担心打开/关闭文件两次。有没有其他可行的方法?

我发现可以通过在
r+
模式下打开文件并使用seek来实现这一点。前三行代码本质上是相同的,但随后我将要前置的行存储在一个变量中。这允许我a)将行写入文件中的第一个位置,b)将原始文件内容写入文件中的位置,该位置等于所加行的长度

set fileName [file join $appContentDir deleteBinDir.js]
set _fileR [open $fileName r+]
set fileContent [read $_fileR]

set preamble "var path = '[file join $appNwDir bin]';\n"
seek $_fileR 0
puts $_fileR $preamble

seek $_fileR [string length $preamble]
puts $_fileR $fileContent
close $_fileR

唯一的区别是,在预加行之后没有第二个新行,这可能是可以纠正的,但在功能上没有区别。

您可以通过这样做来节省一些时间:

set fileName [file join $appContentDir deleteBinDir.js]
set _fileR [open $fileName r+]
set fileContent [read $_fileR]

set preamble "var path = '[file join $appNwDir bin]';\n"
seek $_fileR 0
puts $_fileR $preamble\n$fileContent
close $_fileR
还是这个

package require fileutil
set fileName [file join $appContentDir deleteBinDir.js]
set preamble "var path = '[file join $appNwDir bin]';\n"
::fileutil::insertIntoFile $fileName 0 $preamble\n 
文件:

使用可能会更快:

file rename file file.orig
set fin [open file.orig r]
set fout [open file w]

puts $fout "first line"
fcopy $fin $fout

close $fin
close $fout
file delete file.orig

覆盖文件的一部分时,请记住,文件其余内容在磁盘上的字节位置不会移动。@DonalFellows是的,我在第一次尝试时发现了这一点,当时我只执行了
seek$\u文件管理器0;放入$\u fileR$preamble
,文件的前几十个字节就消失了。这时我意识到我必须随后执行
seek$\u fileR[string length$preamble];放入$\u fileR$fileContent