我有这样一个函数:
int GetBytes(char *loc, int Bytes)
{
int BytesRead=0;
int j = 0;
int i = 0;
int fileloc = 0;
unsigned char TmpLoc[500];
unsigned char TmpLoc1[500];
strcpy(loc,"");
Bytes = Bytes / 2;
BytesRead = fread(TmpLoc, 1, Bytes,PrcFile);
/*Start of conversion*/
if (ebcidic_flag[0] == 'Y')
{
for (i=0; i < BytesRead; i++)
{
j = i * 2;
sprintf(TmpLoc1, "%x", TmpLoc[i]);
if (strlen(TmpLoc1) < 2)
{
strcat(&loc[j], "0");
j++;
}
strcat (&loc[j],TmpLoc1);
}
}
for (i=0;i<(BytesRead*2);i++)
{
if ((loc[i] >= 0x60) & (loc[i] <= 0x7a))
loc[i] = loc[i] & 0xdf;
}
/*End of conversion*/
TotalBytes = TotalBytes + BytesRead;
return (BytesRead * 2);
}
当我评论转换逻辑时的问题,fread
读取整个文件。
但是当转换逻辑被激活时,fread
不会读取整个文件。
例如,如果我有一个 30000 字节的文件,它可能只读取 1210 字节然后返回零。
我的转换逻辑有问题吗?
按要求准确读取16382,之后只读取2个字节返回0,我尝试了不同的文件,结果是一样的
最佳答案
您的转换逻辑假定读取的字节数与您的预期完全相同。不幸的是,情况并非如此。因此,在您的循环中,您需要将其更改为查看实际读取的字节:
for (i=0;i<BytesRead;i++)
和
for (i=0;i<(BytesRead*2);i++)
但除此之外,因为输入/输出是缓冲的,而且您可能无法一次获得所有想要的字节。所以最好的办法是将 fread 本身放入一个循环中,这样你就可以检测到实际结束的时间,而不是假设你可以一次读取所有内容:
int TotalRead = 0;
int BytesRead;
while(TotalRead < Bytes && (BytesRead = fread(TmpLoc, 1, Bytes - TotalRead,PrcFile)) > 0) {
/* do your converting and needed stuff here */
TotalRead += BytesRead;
}
这样您就可以一直阅读到文件末尾。当然,您也可以始终检查读取的最大字节数。
关于c - C 中 ASCII 到 HEX 的转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9197846/