在读取文件过程中的一个小问题-fread和fwrite
最近 在捣鼓图片的插值,本来用的opencv的几个读取像素的库函数,结果页挺好的。后来总觉得opencv有点灰主流,干脆直接用C、c++语言实现好了。但是总是在文件操作的fread和fwrite有问题,(输出的结果有问题)。自己写了个小实验,问题也是这样。
下面是小实验的代码。我先贴出来;
#include <iostream>
#include <fstream>
using namespace std;
#define Width 5
#define Height 5
#define Center_X 3
#define Center_Y 3
int CreateImageFile(const char* filename);
unsigned int ReadImage(const char* filename,int index_x, int index_y);
int main()
{
CreateImageFile("000.fit");
unsigned int result = ReadImage("000.fit",0,0);
cout<<endl<<result<<endl;
for (int i = 0; i < Height; i++)
{
for (int j = 0; j < Width; j++)
{
cout<<ReadImage("000.fit",i,j)<<" ";
}
cout<<endl;
}
return 0;
}
int CreateImageFile(const char* filename)
{
int i,j;
FILE* file;
unsigned int szPixel[Width][Height]= {0} ;
if(fopen_s(&file,filename,"w+") == 0)
{
//success to open
for (i = 0; i < Height; i++)
{
for (j = 0; j < Width; j++)
{
szPixel[i][j] = 10000 * exp((double)-((i - Center_X)*(i - Center_X) + (j - Center_Y)*(j - Center_Y))/20);
cout<<szPixel[i][j]<<" ";
}
cout<<endl;
}
for (i = 0;i < Height; i++)
{
fwrite(szPixel[i], sizeof(unsigned int), Width, file);
}
fclose(file);
}
else
{
cerr<<"cannot open the file :"<<filename<<endl;
}
return 0;
}
unsigned int ReadImage(const char* filename,int index_x, int index_y)
{
FILE* file;
//int i,j;
unsigned int szPixel[Width] = {0};
//make sure the formating parameters is valid
if (index_x < 0 || index_x >= Height || index_y < 0 || index_y >= Width )
{
cerr<<"the index out of range";
}
//open the file
if(fopen_s(&file, filename, "r+") == 0)
{
//open file success
fseek(file, index_y*Width*sizeof(unsigned int), SEEK_SET);
fread(szPixel, sizeof(unsigned int), Width, file);
fclose(file);
}
else
{
cerr<<"fail to open the file :"<<filename<<endl;
}
return szPixel[index_x];
}
运行的结果 总是前几行的数据正确,后面的有几列就不对了
不知道为什么,大家看看问题在哪里?
[解决办法]
if(fopen_s(&file,filename,"w+") == 0)
==》
if(fopen_s(&file,filename,"wb+") == 0)
if(fopen_s(&file, filename, "r+") == 0)
=》
if(fopen_s(&file, filename, "rb+") == 0)
都是二进制的,于是都地加 b。先改了再看看