我正在努力解决K&R C编程书,要求编写一个低级I/O程序,从文件中读取文本并将其打印在屏幕上,如果命令行中没有给出输入文件,则必须从STDIN中获取输入并在屏幕上打印。我认为我已经解决了这个问题,我的代码如下:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
void llfilecopy (int, int);
int main(int argc, char *argv[])
{
int ifd, i = 1;
printf("buffer = %d", BUFSIZ);
if (argc == 1)
llfilecopy (0, 1);
else
{
while (--argc > 0)
{
if ((ifd = open(argv[i++], O_RDONLY, 0)) == EOF)
{
printf("cat: cant open %s\n", *argv);
return 1;
}
else
{
llfilecopy (ifd, 1);
printf ("\n\n");
close(ifd);
}
}
}
return 0;
}
void llfilecopy (int ifd, int ofd)
{
char buff [BUFSIZ];
int n;
while ((n = read (ifd, buff, BUFSIZ)) > 0)
{
if (write (1, buff, n) != n)
printf ("cat: write error on stdout");
}
}
然而,我面临着一个我无法解释的有趣问题。
请注意main()后第3行中的printf语句。如果我使用以下内容
printf("buffer = %d", BUFSIZ);
在屏幕上打印文件后执行此printf。
但是,如果我添加一个“\n”,即e。
printf("buffer = %d\n", BUFSIZ);
在将文件打印到屏幕之前执行printf。
也许这只是我的一个愚蠢的错误。你能指出这里出了什么问题吗?非常感谢。
我正在使用在线GDB-GCC C编译器
https://www.onlinegdb.com/online_c_compiler#