|
CS471/571 - Operating Systems
| Displaying exercises/e1/solution/to.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define K 1024
/**
* This program should open a file (file-name given on the command line,) and
* write to it all the data that is read from the standard input. You may only
* use the kernel system calls for I/O, you may not use any C standard library
* I/O calls. The file opened should be created if it does not exist and
* truncated if it does. An error should be displayed if the file cannot be
* opened and the program should return an non-successful return value.
*
* This program should do I/O in blocks of at least 1K at a time, it is not
* correct to read and write only 1 byte at a time.
*/
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("Usage: to <filename>\n");
return 1;
}
int r, fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0666);
char buf[K];
if (fd < 0) {
perror("File open");
return 1;
}
while( (r = read(STDIN_FILENO, buf, K)) > 0) {
write(fd, buf, r);
}
close(fd);
return 0;
}
|