如何向已有文件中追加数据

4
在 Chapel 中,我们可以使用 open() + iomode.cw 打开一个文件进行写入,例如:
var fout = open( "foo.dat", iomode.cw );   // create a file for writing
var cout = fout.writer();                  // make a channel
cout.writeln( 1.23 );
cout.close();
fout.close();

或通过openwriter()创建一个通道,如下所示:

var cout = openwriter( "foo.dat" );
cout.writef( "n = %10i, x = %15.7r\n", 100, 1.23 );
cout.close();

但是似乎没有对应于“追加”模式的选项(在IO页面中)。当前是否不提供此选项,如果不提供,则是否有惯用的方法来打开文件并附加数据?

1个回答

4

截至Chapel 1.20版本,不支持IO的附加模式。在支持前,您可以使用以下解决方法:

// Open a file for reading and writing
var fout = open("foo.dat", iomode.rw);

// Position a writing channel at the end of the file
var cout = fout.openAppender();

cout.writeln(1.23);

cout.close();
fout.close();

/* Create a writer channel with a starting offset at the end of the file */
proc file.openAppender() {
  var writer = this.writer(start=this.length());
  return writer;
}

关于Chapel,在GitHub上有一个未解决的功能请求,希望增加追加模式。更多信息请查看#9992问题。


谢谢!代码在我的电脑上运行良好(假设foo.dat已经存在)。 - minibean

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接