システムコールwriteを用いた簡単なプログラム


/* simple_filecopy.c*/
#include<unistd.h> /* read, write */
#include<sys/stat.h> /* open */
#include<fcntl.h> /**/
#include<stdlib.h> /* exit */

/*
#include <unistd.h>
  size_t read(int fildes, void *buf, size_t nbytes);

#include <unistd.h>
  size_t write(int fildes, const void *buf, size_t nbytes);

#include <stdlib.h>
  void exit(int status);

#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
  int open(const char *path, int oflags);
  int open(const char *path, int oflags, mode_t mode);
 

#include <unistd.h>
 int close(int fildes);
*/
int main()
{
char c;
int in, out;
/*open establishes an access path to a file or device. If successful, it returns a file descriptor
that can be used in read, write and other system calls. */
in = open("file.in", O_RDONLY);
/*When we create a file using the O_CREAT flag with open, we must use the three parameter form. mode, the third parameter, is made from a bitwise OR of the flags defined in the header file sys/stat.h
 */
/*S_IRUSR : Read permission, owner. S_IWUSR : Write permission, owner. */
out = open("file.out", O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);

while(read(in,&c,1) == 1)
write(out, &c,1);

/* When a program exits, all open file descriptors are automatically closed,
 so we don't need to close them explicitly */
exit(0);
}


#以下実行例

$ echo "We are the world" > file.in
$ cat file.in
We are the world
$ ./simple_filecopy
$ cat file.out
We are the world