fwrite会创建损坏的文件

时间:2014-08-05 10:07:39

标签: c fwrite

我遇到了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);
    }

1 个答案:

答案 0 :(得分:0)

有一些错误......

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,并分别执行每个颜色组件。

相关问题