我正在尝试将结构写入文件,在末尾写一个字符串以使文件的大小为1M,然后将结构读取到另一个变量。 结构的大小是4424字节,但读取返回2018 - 无论我再次运行多少次,它都不会读取任何字节。这没有意义,因为我只是写了4K字节。
这是结构:
typedef struct alloc_table_record{
char fileName[MAXIMUM_FILE_NUM]; //100
ssize_t fileSize;
mode_t fileProtect;
time_t insertionTime;
ssize_t db1Size;
off_t db1Offset;
ssize_t db2Size;
off_t db2Offset;
ssize_t db3Size;
off_t db3Offset;
bool valid;
}TableRec;
typedef struct catalog_t{
off_t totalSize;
ssize_t overallSize;
time_t creatTime;
time_t modTime;
short fileAmount;
short blocksInUse;
ssize_t lastSpot;
TableRec allocTable[MAXIMUM_FILE_NUM]; //100
}Catalog;
代码:
Catalog newCat;
newCat.lastSpot = 1024*1024; //some input value
//... initializing field
int fd = open(fileName,O_RDWR | O_CREAT | O_TRUNC,0755);
ssize_t wrote = write(fd, &newCat, sizeof(newCat)); //wrote is 4424
off_t offset = lseek(fd, newCat.lastSpot - 1, SEEK_SET);
wrote = write(fd, "0", 1);
lseek(fd,0,SEEK_SET);
Catalog obj2;
ssize_t readGood = read(fd, &obj2, sizeof(obj2)); //readGood is 2018
ssize_t readGood2 = read(fd, (char*)(&obj2) + readGood, sizeof(obj2)-readGood); // readGood2 is 0