将 Tcl 中命令的输出重定向到文件时,文件以 DOS 格式生成
When Redirecting output of a command in Tcl to file, file is getting generated in DOS format
我想在 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
Notice ^M 在执行cat 操作时打印。这是因为保存文件的 DOS 风格格式。
Tcl 允许您使用 chan configure
命令(也称为 fconfigure
)控制通道(文件句柄、套接字等)的行结束转换。特别是,您希望将 -translation
选项配置为 lf
(用于换行)或 binary
(同时设置一些其他内容)。 Tcl 忽略 C stdio 中的设置,因为它直接访问OS 来执行I/O,并且行结束翻译在那个时候没有完成。
根据您的具体操作,将其中之一放入您的脚本中:
chan configure stdout -translation lf
chan configure stdout -translation binary
您还可以从 C:
设置频道翻译
/* Guess what 'chan configure' is a wrapper around? */
Tcl_SetChannelOption(interp, stdoutChannel, "-translation", "binary");
我想在 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
Notice ^M 在执行cat 操作时打印。这是因为保存文件的 DOS 风格格式。
Tcl 允许您使用 chan configure
命令(也称为 fconfigure
)控制通道(文件句柄、套接字等)的行结束转换。特别是,您希望将 -translation
选项配置为 lf
(用于换行)或 binary
(同时设置一些其他内容)。 Tcl 忽略 C stdio 中的设置,因为它直接访问OS 来执行I/O,并且行结束翻译在那个时候没有完成。
根据您的具体操作,将其中之一放入您的脚本中:
chan configure stdout -translation lf
chan configure stdout -translation binary
您还可以从 C:
设置频道翻译/* Guess what 'chan configure' is a wrapper around? */
Tcl_SetChannelOption(interp, stdoutChannel, "-translation", "binary");