[问] fwrite的问题
Posted by bianbian on 2007-07-28 12:52
本文Tags: fwrite
fwrite(const void *buffer,size_t size, size_t count, FILE *fp);
这个似乎是把内存里的一股脑儿write到文件里去。
如果buffer是new出来的一大堆数据,有可能在内存里是分片存的,这时候一大堆一起写就有问题。
我不清楚是VC6的问题,还是fwrite本来就有这个问题:
- ....
- double *_bt[k] = new double[_header.wHeight * _header.wWidth];
- ....
- for(k=0; k < _GRAY_BANDS; k++)
- {
- //用:fwrite(_bt[k], sizeof(double), _header.wHeight * _header.wWidth, fp2); 就不对
- //必须一个一个保存
- for(int j=0; j < _header.wHeight; j++)
- {
- for(int i=0; i < _header.wWidth; i++)
- {
- int idx = j * _header.wHeight + i;
- fwrite(& _bt[k][idx], sizeof(double), 1, fp2);
- }
- }
- delete[] _bt[k];
- }
- fclose(fp2);
哪位经过告诉我一声。
标签: fwrite遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道
July 28th, 2007 at 01:51:13
摘自 C 语言标准
size_t fwrite(const void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream);
The fwrite function writes, from the array pointed to by ptr, up to nmemb elements whose size is specified by size, to the stream pointed to by stream. For each object, size calls are made to the fputc function, taking the values (in order) from an array of unsigned char exactly overlaying the object. The file position indicator for the stream (if defined) is advanced by the number of characters successfully written. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate.
July 29th, 2007 at 07:38:57
我知道怎么回事了。并不是内存分配的问题。
而是 _header.wHeight, _header.wWidth 这两个数据的类型是WORD(unsigned short),两个字节,最大能承受FF*FF的大小。
相乘以后C语言以左边的类型为准,还是两个字节来存放乘积,就溢出了。
August 1st, 2007 at 08:49:41
o