#post
我的变量名并不重要!此代码将在有效时被删除!
#post
好的,所以我在 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;
}
最佳答案
这里有一些奇怪的事情:
int i = 0;
for(i=0;i<alen;++i)
{
fread(&cha[i],sizeof(CHR),bsize,inFile);
printf("[%i]%s",i,cha[i]);
}
您不能在打印之前终止缓冲区(正如 RageZ 指出的那样)。
您在每次循环重复时递增
i
,但每次您将 84 个字符 (bsize
) 读入&cha[i]
.我认为这应该意味着您只能看到每 84 个字符。
另外,如果我是你,我会每次都检查 fread
的返回值。不能保证总是返回您期望的字节数。
编辑:您正在阅读的 block 的大小很好。我被 typedef 弄糊涂了一分钟。每次您将 i
递增 1 时,它都会按照您的预期将指针前进 84*sizeof(CHR)
。尽管如此,您仍不能保证它读取了您认为的字节数。如果它短了,那么缓冲区中就会留下垃圾:假设它读取了 60 个字符,那么在下一次读取的插入点之前会留下 24 个垃圾字符。
关于c++ - 带有 fread 的随机字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1851078/