想要填充元数据结构

这里我有一个目录,其中包含多个文件。

我想在一个结构中填充这些文件的所有信息。

我有两个结构如下。

struct files { char *file_name; int file_size; }; typedef struct file_header { int file_count; struct files file[variable as per number of files]; } metadata; 

我想制作一个包含有关这些文件的所有信息的标题。

就像我有3个文件,而不是我想在file_count = 3中使这个结构像这样,我怎么能分配第二个变量值? 并希望按文件存储文件名和文件大小。

我想要这样的文件结构

 file_count = 3 file[0].file_name = "a.txt" file[0].file_size = 1024 file[1].file_name = "b.txt" file[1].file_size = 818 file[2].file_name = "c.txt" file[2].file_size = 452 

我有关于文件名和文件大小的所有逻辑但是我如何在这个结构中填充这些东西。

代码:

 #include  #include  #include  #include  #include  #include  #include  char path[1024] = "/home/test/main/Integration/testing/package_DIR"; //int count = 5; struct files { char *file_name; int file_size; }; typedef struct file_header { int file_count; struct files file[5]; } metadata; metadata *create_header(); int main() { FILE *file = fopen("/home/test/main/Integration/testing/file.txt", "w"); metadata *header; header = create_header(); if(header != NULL) { printf("size of Header is %d\n",sizeof(metadata)); } if (file != NULL) { if (fwrite(&header, sizeof(metadata), 1, file) < 1) { puts("short count on fwrite"); } fclose(file); } file = fopen("/home/test/main/Integration/testing/file.txt", "rb"); if (file != NULL) { metadata header = { 0 }; if (fread(&header, sizeof(header), 1, file) d_type == DT_REG) { /* If the entry is a regular file */ header->file[file_count].file_name = (char *)malloc(sizeof(char)*strlen(entry->d_name)); strcpy(header->file[file_count].file_name,entry->d_name); //Put static but i have logic for this i will apply later. header->file[file_count].file_size = 10; file_count++; } } header->file_count = file_count; closedir(dirp); //printf("File Count : %d\n", file_count); return header; } 

输出:

 size of Header is 88 ile Name =  ~8 File count = 29205120 File Size = -586425488 

它显示了不同的输出。 那么这里有什么问题吗?

除此之外,你在指针变量上使用sizeof ,但似乎认为它给你指向的对象的大小。 它没有。 为此,使用星号运算符使表达式具有指针指向的类型:

 printf("size of Header is %d\n", sizeof *metadata); 

作为旁注,请注意sizeof不是函数,因此您不需要括号。 当你看到括号时,那就是它们是表达式(演员表)的一部分。

你没有为null终结符留下足够的空间:

 header->file[file_count].file_name = (char *)malloc(sizeof(char)*strlen(entry->d_name));