我必须基于struct
在c中实现一个构造函数:
struct Node {
char name[MAX_NAME_LEN + 1];
NodeType type;
union {
struct {
Entry* entries; // list of directory entries
} dir;
struct {
void* contents; // any binary data of the given length
int length;
} file;
};
};
现在我想构建一个file
的构造函数,指向内容并以字节为单位保存长度,但不知何故我不知道该怎么做...
下面是我的尝试:我知道我必须为此分配空间,但我如何使这个指针的东西?
Node* new_file(char* name) {
Node* ptr_file = xmalloc(sizeof(Node));
ptr_file->name;
return NULL;
}
2条答案
按热度按时间9avjhtql1#
typedef struct { ... } Node
才能编译代码。ptr_file->dir.entries
或ptr_file->file.contents
。ptr_file->entries;
。请注意,匿名结构体/联合体在ISO 9899:2011版本的C语言中被添加到了该语言中,因此您需要使用一个相当现代的编译器来使用它们。
顺便说一句,
void*
可能没有任何意义。我认为您正在尝试做的是:nukf8bse2#
使用
Node* new_file(char* name)
时,Node
尚未定义。代码需要typedef struct Node Node;
或类似代码。这项任务面临的一大挑战是许多潜在的错误可能会悄悄进入:文件名太长,内存分配失败,fopen打开失败,读取失败,文件太长,...
int length;
应为size_t length;
,因为文件可能比INT_MAX
长,但仍适合分配。new_file(char* name)
看起来应该读取一个文件。让我们创建一个辅助函数,因为需要不同程度的健壮性。下面的函数通常“工作”,但属于技术UB(查找到二进制文件的末尾)。根据需要进行调整。说明性的、未经测试的代码:
现在
new_file
更容易了。