好吧,所以我在stdio.h中使用fread来读取文本文件.问题是我一直在阅读文字文件中不存在的随机字节.我假设他们是文件方案的一部分,但我只是想确保它不是我的代码.
#include "stdafx.h"
#ifdef WIN32
#include <io.h>
#else
#include <sys/io.h>
#endif
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include "n_script_timer.h"
//using namespace std;
#ifdef _INC_WCHAR
typedef wchar_t CHR;
#else
typedef char CHR;
#endif
int _tmain(int argc, CHR* argv[])
{
#ifndef _DEBUG
if(argc == 1)
{
printf("You must drag a file onto this program to run it.");
scanf("%*c");
return 0;
}
CHR* fname = argv[1];
#else
#ifdef _INC_WCHAR
const CHR fname[16] = L"f:\\deleteme.bin";
#else
const CHR fname[16] = "f:\\deleteme.bin";
#endif
#endif
FILE* inFile;
long len;
struct Script_Timer a;
//static const int bsize = 4096*6;
static const int bsize = 84;
typedef CHR chhh[bsize];
int alen;
printf("#Opening File '%s' ...\n",fname);
#ifdef _INC_WCHAR
if((inFile = _wfopen(fname,L"rb")) == NULL)
#else
if((inFile = fopen(fname,"r")) == NULL)
#endif
{
printf("Error opening file '%s' ",fname);
return 0;
}
fseek(inFile,SEEK_SET,0);
#ifdef _WIN32
len = _filelength( inFile->_file );
#else
len = _filelength(inFile->_fileno);
#endif
printf(" !FileLength: %d\n",len);
printf("#Creating Buffers...\n");
if(((float)len/(float)bsize) > (len/bsize))
{
alen = (len/bsize) + 1;
}
else alen = (len/bsize);
#ifdef WIN32
//chhh *cha = new chhh[alen];
chhh cha[alen];
#else
chhh cha[alen];
#endif
printf("#Reading File...\n");
Start_ST(&a);
int i = 0;
for(i=0;i<alen;++i)
{
fread(&cha[i],sizeof(CHR),bsize,inFile);
printf("[%i]%s",i,cha[i]);
}
End_ST(&a);
fclose(inFile);
printf("Characters per millisecond: %f \n",((float)len/a.milliseconds));
printf("Characters per second: %f \n",((float)len/a.milliseconds) * 1000);
scanf("%*c");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这里有几件奇怪的事情:
int i = 0;
for(i=0;i<alen;++i)
{
fread(&cha[i],sizeof(CHR),bsize,inFile);
printf("[%i]%s",i,cha[i]);
}
Run Code Online (Sandbox Code Playgroud)
在打印缓冲区之前,不要将其终止(如RageZ指出的那样).
你i在每次循环重复时递增,但每次你读取84个chars(bsize)&cha[i].我认为这应该意味着你只看到每个第84个角色.
此外,如果我是你,我会检查fread每次的返回值.不能保证始终返回您期望的字节数.
编辑:您正在阅读的块的大小很好.我被typedef弄糊涂了一分钟.每次递增i1时,它会按指定的方式前进指针84*sizeof(CHR).但是,您无法保证它会读取您认为它所执行的字节数.如果它变短了那么你将在缓冲区中留下垃圾:说它读取60个字符,在下一次读取的插入点之前留下24个垃圾字符.
| 归档时间: |
|
| 查看次数: |
1083 次 |
| 最近记录: |