c - fwrite 创建损坏的文件

标签 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);
    }

最佳答案

有一些错误...

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/

相关文章:

c - 使用一些 malloc 内存而不是使用文件来虚拟化 fopen

c - 为什么 MISRA C 声明指针的副本会导致内存异常?

C 函数指针转换为 void 指针

c - 哪个效率更高 : char a[10]; OR char *a; a = malloc(10);

c - ANSI C 我在 fwrite 和 fread 上做错了什么?

c - 如何获取结构数据的hexdump

计算文件中除空格之外的单词数

c - 哪种方法可以更快地确定奇偶性?

php - 在本地主机上使用瑞典字符 php 进行 fwrite

C 指针、结构和 fwrite