ちょっと仕事で調べる必要があって、freadの検証。
ソースコード
/*
main.cpp
*/
#include <stdio.h>
#include <time.h>
#include <windows.h>
#include <mmsystem.h>
#pragma comment(lib, "Winmm.lib")
#define BUF_SIZE 1024
static LARGE_INTEGER nFreq, nBefore, nAfter;
static LONGLONG DiffTime();
static int test1(FILE *fp, const char *fileName, char *buf);
static int test2(FILE *fp, const char *fileName, char *buf);
int main(int argc, char *argv[])
{
FILE *fp = NULL;
char buf[BUF_SIZE];
const char *fileName = "D:\\test.dat";
QueryPerformanceFrequency(&nFreq);
test1(fp, fileName, buf);
test1(fp, fileName, buf);
test2(fp, fileName, buf);
test2(fp, fileName, buf);
return 0;
}
LONGLONG DiffTime()
{
return (nAfter.QuadPart - nBefore.QuadPart) * 1000 / nFreq.QuadPart;
}
int test1(FILE *fp, const char *fileName, char *buf)
{
int err = 0;
int readLength = 0;
int readTotal = 0;
printf("--- 実験1 ---\n");
fp = fopen(fileName, "rb");
if (fp == NULL) {
printf("open error. filename=%s\n", fileName);
return -1;
}
QueryPerformanceCounter(&nBefore);
while(1) {
readLength = fread(buf, sizeof(char), BUF_SIZE, fp);
readTotal += readLength;
if (readLength != 1024) {
err = ferror(fp);
printf("fread length unmatch. ferror=%d, readLength=%d\n", err, readLength);
break;
}
}
QueryPerformanceCounter(&nAfter);
printf("readTotal=%d, time=%dms\n", readTotal, DiffTime());
fclose(fp);
return 0;
}
int test2(FILE *fp, const char *fileName, char *buf)
{
int err = 0;
int readLength = 0;
int readTotal = 0;
printf("--- 実験2 ---\n");
fp = fopen(fileName, "rb");
if (fp == NULL) {
printf("open error. filename=%s\n", fileName);
return -1;
}
QueryPerformanceCounter(&nBefore);
while(1) {
readLength = fread(buf, BUF_SIZE, 1, fp) * BUF_SIZE;
readTotal += readLength;
if (readLength != 1024) {
err = ferror(fp);
if (err != 0) {
printf("fread error. ferror=%d, readLength=%d\n", err, readLength);
break;
} else {
printf("eof. ferror=%d, readLength=%d\n", err, readLength);
break;
}
}
}
QueryPerformanceCounter(&nAfter);
printf("readTotal=%d, time=%dms\n", readTotal, DiffTime());
fclose(fp);
return 0;
}
結果
--- 実験1 --- fread length unmatch. ferror=0, readLength=344 readTotal=336724312, time=4591ms --- 実験1 --- fread length unmatch. ferror=0, readLength=344 readTotal=336724312, time=3490ms --- 実験2 --- eof. ferror=0, readLength=0 readTotal=336723968, time=3024ms --- 実験2 --- eof. ferror=0, readLength=0 readTotal=336723968, time=3349ms