我遇到了 fwrite 损坏文件的问题。 该程序背后的想法是创建一个 RAW 图像文件,该文件存在于我插入到名为 Colors[] 的数组中的像素中。基本上应该是把不同颜色的直线放入阵列中。现在我尝试了很多方法将其写入文件,但如果它没有以位模式写出,它就无法在我创建的 RAW 图像显示程序上运行,尽管其他 RAW 图像确实可以运行。 有没有更简单的方法可以做到我想做的事情? 该程序的一个版本中,我使用字符数组来填充缓冲区,但它的代码要多得多。 eX//unsigned char Col[] = {'f','f','f','f','f','f'};
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *readFile(char *fileName);
int main()
{
unsigned int i;
//Pixels in 24Bit mode
unsigned int Colors[] = {0x00ff00,0x00ffff,0xffff00,0xffff00};
FILE *fpw;
fpw=fopen("MF.bin", "wb");
/*A Buffer array for the pixels to be stored in before fwrite will be used to
dump the entire array to a file.
640pixels by 480pixels * 3(each pixel has 3 ints)
*/
unsigned int Buff[640*480*3];
int y,z,CP=0;
unsigned long x;
for (y=0;y<=(480);y++)
{
if (x>=640)
{
CP = 0;
}
for(x=0;x<=640;x++)//3840);x++)
{
if ((x>=320))
{
CP = 1;
}
if ((x>=159) && (x<319))
{
CP = 1;
}
else if ((x>=319) && (x<439))
{
CP = 2;
}
else if ((x>=439) && (x<640))
{
CP = 0;
}
else if (x>=640)
{
CP =0;
}
Buff[480*y + x] = Colors[CP];
printf("%u--%u,%u\n",(480*y + x),Buff[480 + x], Colors[CP]);
}
unsigned int xx = fwrite(Buff, 1, sizeof(Buff)/sizeof(Buff[0]), fpw);
printf("--&z--",xx);
}
fclose(fpw);
}
最佳答案
有一些错误...
Buff[480*y + x] = Colors[CP];
应该是
Buff[640*y + x] = Colors[CP];
和y
循环应该是 < 480
不是<=
,对于 x 来说也是如此。
您使用的是无符号整数,因此您不需要在 new
中乘以 3 。使用 fwrite 直接写出 24 位数据不会像这样工作,因为您有一个 32 位数据的数组,并且您对要写入的字节数的计算不正确(您需要乘法而不是除法,但如上所述也会是错误的,因为你有 32 位数据而不是 24)。
没有 24 位数据类型,因此您应该使用 unsigned char 而不是 unsigned long 数组,并单独执行每个颜色分量。
关于c - fwrite 创建损坏的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25136158/