stio.hを用いてファイルコピープログラムを作る


システムコールはとにかく実行するのに時間がかかるのがネックです。
stdio.hで実現される一連の仕組みは、バッファという空間を作ってそこにデータを貯めていき、いっぱいになったら、システムをコールを呼び出すというようなものです。
システムコールを呼び出す回数を減らせるため、はるかに高速なプログラムを書くことができるそうです。

/* simple_filecopy_2.c*/
/*  character−by−character copy is accomplished using
calls to the functions referenced in stdio.h. */
#include<stdio.h>  /* fopen, fgetc, fputc*/
#include<stdlib.h> /* exit */

/*
In many ways, you use this library in the same way
that you use low−level file descriptors.
We need to open a file to establish an access path.
This returns a value that is used as a parameter to other I/O library functions.
The equivalent of the low−level file descriptor is called a stream
and is implemented as a pointer to a structure, a FILE *.
*/

/* Three file streams are automatically opened when a program is started.
   They are stdin, stdout and stderr. */


/*
#include <stdio.h>
FILE *fopen(const char *filename, const char *mode);

//The fgetc function returns the next byte, as a character, from a file stream.
#include <stdio.h>
int fgetc(FILE *stream);
int getc(FILE *stream);
int getchar();


//The fputc function writes a character to an output file stream.
//It returns the value it has written, or EOF on failure.
//As with fgetc/getc, the function putc is equivalent to fputc, but you may implement it as a macro.
//The putchar function is equivalent to putc(c,stdout),
//writing a single character to the standard output
#include <stdio.h>
int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);

*/

int main()
{
int c;
FILE *in, *out;

in = fopen("file.in", "r");
out = fopen("file.out", "w");

while((c = fgetc(in)) != EOF)
fputc(c, out);

exit(0);
}


#以下実行例
$ gcc -o simple_filecopy_2 simple_filecopy_2.c

$ echo "She loves you" > file.in
$ cat file.in
She loves you
$ ./simple_filecopy_2
$ cat file.out
She loves you