c++ - 将 Tcl 中命令的输出重定向到文件时,文件以 DOS 格式生成

标签 c++ c tcl

<分区>

我想在 Tcl 中开发一个命令“redirect”,它将要执行的命令作为参数并将命令的输出重定向到用户提供的文件。我正在使用下面的代码并且运行良好。这段代码的唯一问题是文件是以 DOS 格式创建的。我该如何摆脱这种情况,因为格式应该是 Unix 风格而不是 DOS?

我尝试在 VI 编辑器和其他解决方法中设置 :set binary vim +"argdo setlocal ff=unix"+wqa 但是,找不到以 DOS 格式创建此文件的任何原因。

Tcl_Channel stdoutChannel = Tcl_GetStdChannel(TCL_STDOUT);

Tcl_Channel stderrChannel = Tcl_GetStdChannel(TCL_STDERR);

if(stdoutChannel) {

  Tcl_Flush(stdoutChannel);

}

if(stderrChannel) {

  Tcl_Flush(stderrChannel);

}

FILE* filePtr = fopen(filename, "wb");

int pfd = fileno(filePtr);

int saved = dup(1);

close(1);

Tcl_Obj* commandResult = Tcl_NewStringObj(command,strlen(command));

dup2(pfd,STDOUT_FILENO);

Tcl_EvalObj(TBXslaveInterp,commandResult);

close(pfd);

fflush(stdout);

// restore it back

dup2(saved, 1);

close(saved);

return TCL_OK;

输出

Command executed : 
redirect myfile {puts "Inside Tcl"}

Viewing File in VI at the bottom shows:

"myfile" [dos] 1L, 12C


 cat myfile 

 Inside Tcl^M

注意 ^M 在执行 cat 操作时打印。这是因为保存文件的 DOS 样式格式。

最佳答案

Tcl 允许您使用 chan configure 命令(也称为 fconfigure)控制 channel (文件句柄、套接字等)的行结束转换。特别是,您希望将 -translation 选项配置为 lf(用于换行)或 binary(设置一些其他事情也是如此)。 Tcl 忽略 C stdio 中的设置,因为它直接访问操作系统以执行 I/O,并且此时未完成行结束转换。

根据您的具体操作,将其中之一放入您的脚本中:

chan configure stdout -translation lf
chan configure stdout -translation binary

您还可以从 C: 设置 channel 翻译

/* Guess what 'chan configure' is a wrapper around? */
Tcl_SetChannelOption(interp, stdoutChannel, "-translation", "binary");

关于c++ - 将 Tcl 中命令的输出重定向到文件时,文件以 DOS 格式生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57689172/

相关文章:

测试用例的c程序代码

找不到最常用的词

C(Linux 上的 gcc): How do i convert a hex string "0xfffffff" to an integer?

tcl - tclsh "$@" "$0" "$@"的用途和作用

floating-point - 当 `expr` 嵌套在 Tcl 中时,为什么算术结果不同?

python - 是否可以在 Python 中定义 Tcl 过程?

c++ - Deadline_timers 的非阻塞 boost io_service

c++ - 通用阶跃函数的最佳数据结构是什么?

c++ - 二进制表达式错误消息的无效操作数

c++ - 查找最大递归深度