使用fread来改变结构值C时遇到麻烦

时间:2013-04-03 05:08:42

标签: c struct fwrite fread

我的问题是,我认为......,一切正常,但实际的块变量没有变化。它是BLOCK大小,为512字节,第一个字节为block.head [0,1,2,3]。所以我的程序使用block.head []来查看它正在读取的文件块的前四个字节是否匹配。

所以我认为正在发生的是它正在将BLOCK数量读入文件中,但实际上并没有改变block.head变量。因此即使它正在读取文件的某个部分,它也不会改变它需要比较的变量。我认为在fread参数中编写& block会改变它,但事实并非如此。

有什么想法吗?

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef uint8_t  BYTE;
typedef uint32_t DWORD;

typedef struct
{
    BYTE head[4];
    DWORD restofblock[127];
}
BLOCK;

int main (void)
{
    //open card.raw
    FILE* fp = fopen("file.file", "r");

    //default name for new files is new000.jpg
    char outfile[10] = "new000.jpg";

    // char* infile = argv[1];
    // FILE* inptr = fopen(infile, "r");

    FILE* output;
    output = NULL;

    //define a black
    BLOCK block;

    //While we haven't read past the end of the file
    while (block.head[1] != EOF)
    {
        //read a BLOCK of the .raw file
        fread(&block, sizeof(BLOCK), 1, fp);

        //dual "if" statements because I couldn't figure out how to combine them
        //checks to see if the first four BYTES of BLOCK block are a JPEG header
        if (block.head[0] == 255 && block.head[1] == 231 && block.head[2] == 255)
        {
            if (block.head[3] == 239 || block.head[3] == 240)
            {

                fclose(output);

                //designating c as a placeholder for the 3rd 0 in the filename
                //checks to see if c is above or equal to "9".
                //if it is, it resets "9" to "0" and increments the 2nd 0 in the filename by 1
                //if it isn't it adds 1 to the 3rd "0"
                char c = (outfile[5]);
                if (c >= 71) //71 is the ascii equivalent of 9
                {
                    outfile[5] -= 9;
                    outfile[4]++;
                }
                else
                    outfile[5]++;

                //Read forward 1 BLOCK to check for EOF, if EOF is false, read back to original position and print. 
                //Otherwise read back to initial position.
                fread(&block, sizeof(BLOCK), 1, fp);
                if(block.head[0] != EOF)
                {
                    fread(&block, -sizeof(BLOCK), 1, fp);
                    output = fopen(outfile, "w");
                }
                else
                    fread(&block, -sizeof(BLOCK), 1, fp);
            }
        }
        if (output == NULL);

        else
            fwrite(&block, sizeof(BLOCK), 1, output);

   }
    fclose(output);
    fclose(fp);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

而不是

while (block.head[1] != EOF)

您应该阅读:

while (fread(&block, sizeof(BLOCK), 1, fp) > 0)

我找不到您分配head[1] = EOF的任何地方,此外,最初block.head[1]具有垃圾值。因为你没有初始化它并在while条件下使用。