简体   繁体   English

仅在C中读取fseek结构成员

[英]fread fseek struct member only in C

In C I'm trying to select a specific member of a struct and print it out. 在C语言中,我试图选择结构的特定成员并将其打印出来。 I wonder, what is the suggested format for such an operation? 我想知道,这种操作的建议格式是什么? I've tried nearly everything I can think of. 我几乎尝试了所有我能想到的。 I can't seem to limit it to the specific chunk member of the struct. 我似乎不能将其限制为该结构的特定chunk成员。

fseek(in, sizeof(d.contents.datas.chunk), SEEK_SET);
fread(&ch, 1, 1, in);
fprintf(out, "%02x", (int)(ch & 0x00FF));

It seems I can get either all of the struct data, or only one character. 看来我既可以获取所有struct数据,也可以仅获取一个字符。 For some reason the data is also not coming out right, for instance bytes should be the actual bytes , but it's coming out as 1 . 由于某种原因,数据也不正确,例如, bytes应该是实际的bytes ,但是输出为1 Clearly there is something really wrong with the way the data from this struct is being printed. 显然,从该结构打印数据的方式确实存在一些问题。 Could it be to do with big endian vs little endian? 大尾数与小尾数有关系吗? I know the file I'm accessing is big endian. 我知道我正在访问的文件是大字节序。

The struct Im accessing is as follows: 我访问的结构如下:

struct chunkInfo
{
    int chunkInformation; 
    int bytes;

    union
    {
        struct
        {
            long size;     
            char chunk[1];     
        } datas;                 
    } contents;                  
};

You are seeking to the wrong place in the file. 您正在寻找文件中错误的位置。 Assuming the endian of your machine is the same as the endian of the file, then this will work: 假设计算机的字节序与文件的字节序相同,则可以使用:

fseek(in, long(&d.content.data.chunk[0] - &d), SEEK_SET);
fread(&ch, 1, 1, in);
fprintf(out, "%02x", (int)(ch & 0x00FF));

The first line calculates the offset in bytes of chunk in the structure. 第一行以字节为单位计算结构中的偏移量。 You were using the sizeof(chunk) which of course just returns 1. 您使用的是sizeof(chunk),它当然只会返回1。

If the endian is different, then you will have to convert each non char character to the correct endian after reading in the structure. 如果字节序不同,则在读取结构后,必须将每个非char字符转换为正确的字节序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM