[英]Reading correctly from a file
During the course of my program, 在我的课程中,
The 2 functions are: 这两个功能是:
void printFile(char *fileName)
{
char *fileContent=(char *)malloc(200*sizeof(char)); /* sufficiently large buffer */
if((filePtr=fopen(fileName,"r"))==NULL)
{
printf("Error opening %s: %s\n",fileName,strerror(errno));
if( (strcmp(fileName,"/tmp/command.log")==0) || (strcmp(fileName,"/tmp/output.log")==0) ){exitStatus=255;}
}
else
{
while(fscanf(filePtr,"%s",fileContent)!=EOF)
{
printf("%s",fileContent);
printf("%c",fgetc(filePtr));
}
fclose(filePtr);
}
}
void outCopy(char *fileName)
{
char *fileContent=(char *)malloc(200*sizeof(char)); /* sufficiently large buffer */
if( (filePtr=fopen(fileName,"r"))==NULL || (filePtr2=fopen("/tmp/output.log","a"))==NULL )
{
printf("Error opening files: %s\n",strerror(errno));
}
else
{
while(fscanf(filePtr,"%s",fileContent)!=EOF)
{
fprintf(filePtr2,"%s",fileContent);
fprintf(filePtr2,"%c",fgetc(filePtr));
}
fclose(filePtr);
fclose(filePtr2);
}
}
However, my neat little scheme gets disturbed for the output of the ls
command: 但是,我的整洁的小方案对
ls
命令的输出感到不安:
Expected output: 预期产量:
a.c c.c e.c
b.c d.c
Current output: 当前输出:
a.c
b.c
c.c
d.c
e.c
How can I change either or both of my functions to get the proper output? 如何更改其中一个或两个函数以获得正确的输出?
(Please don't suggest using pipes or tees, or I will have to change a major portion of my exec() calling child) (请不要建议使用管道或T恤,否则我将不得不更改我的exec()呼叫孩子的主要部分)
Edit: Please note that both the outCopy()
& the printFile()
are run by the parent . 编辑:请注意,
outCopy()
和printFile()
都由父级运行。 Output has already been dup2()
ed to the required temp file by the child . 输出已是
dup2()
版由孩子所需的临时文件。
Some versions of ls
(including the GNU version used in Linux) detect whether they are being run with a terminal or with a pipe as standard output, and change their formatting. 某些版本的
ls
(包括Linux中使用的GNU版本)会检测它们是使用终端还是使用管道作为标准输出运行,并更改其格式。 If you want exactly the same output, you'll need to create a pseudo-TTY (pty) using the posix_openpt call and friends. 如果你想要完全相同的输出,你需要使用posix_openpt调用和朋友创建一个伪TTY(pty)。 Or you can use the
script
utility, which takes care of this for you. 或者您可以使用
script
实用程序,它会为您处理此问题。
Another option is to use the -C
option to ls
to force columnar layout; 另一种选择是使用
-C
选项ls
迫使柱状布局; however, this may not be exactly the same, as ls
won't know the width of your terminal, and may assume the wrong width. 但是,这可能不完全相同,因为
ls
不知道终端的宽度,并且可能假设宽度错误。 Additionally, other features such as colored output may be missing. 此外,可能缺少其他功能,如彩色输出。
When stdout is not a tty, ls
changes behavior from user-friendly columns to script-friendly lists. 当stdout不是tty时,
ls
会将用户友好列中的行为更改为脚本友好列表。 The flag ls -C
forces columnar output regardless of the type of device stdout is attached to. 标志
ls -C
强制柱状输出,无论附加设备stdout的类型如何。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.