I am trying to solve a problem from the K&R C programming book that requires one to write a low level I/O program which reads text from a file and prints it on screen, if no input file is given in the command line, it must take input from STDIN and print on the screen. I think I have solved the problem and my code is as given below:
#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 (ofd, buff, n) != n)
printf ("cat: write error on stdout");
}
}
However, I am facing a funny problem which I cannot account for. Notice the printf statement in line 3 after main(). If I use the following
printf("buffer = %d", BUFSIZ);
this printf is executed after printing the file on screen. If however I add a '\n' i.e.
printf("buffer = %d\n", BUFSIZ);
the printf is executed before printing the file to screen. Perhaps its just a silly mistake of mine. Can you please point out whats going wrong here? Thank you so much. I am using the online GDB - GCC C compiler https://www.onlinegdb.com/online_c_compiler#
stdoutis by default buffered. This meansprintfor similar functions don't cause the characters to appear on the output device immediately. They are written to an internal buffer instead. The characters appear when the buffer is flushed. K&R should explain this somewhere.printf( ... )withfprintf( stderr, ... )