Linux的读写流声明如下:
#include <stdio.h>
int getc(FILE *fp);
int fgetc(FILE *fp);
int getchar(void);
int ferror(FILE *fp);
int feof(FILE *fp);
void clearerr(FILE *fp);
int ungetc(int c, FILE *fp);
int putc(int c);
int fputc(int c, FILE *fp);
int putchar(void);
首先是 fgetc 和 fputc 测试:
#include <stdio.h>
int main()
{
int c;
while ((c = fgetc(stdin)) != EOF)
if (fputc(c, stdout) == EOF) {
printf("output error\n");
exit(1);
}
if (ferror(stdin)) {
printf("input error\n");
exit(1);
}
return 0;
}
结果:
下面是 getc 和 putc 测试:
下面测试 fgets 和 fputs:
#include <stdio.h>
#define MAXLINE 1024
int main()
{
int c;
char buf[MAXLINE];
while (fgets(buf, MAXLINE, stdin) != 0)
if (fputs(buf, stdout) == EOF) {
printf("output error\n");
exit(1);
}
if (ferror(stdin)) {
printf("input error\n");
exit(1);
}
return 0;
}
结果:
由上述结果可见标准IO的运行效率,fgets 和 fputs 是最快的,当然这是建立在缓冲区足够大的前提下,如果缓冲长度很小,比如为2,那么效率会很差,结果见下图:
这里我们的输入文件有 81M,缓冲区设置小了会增加系统掉用的次数,系统调用与普通的函数调用相比通常需要花费更多的时间。