10 struct file
*tfs_open(struct tfs_sb_info
*sbi
, const char *filename
)
15 inode
= tfs_namei(sbi
, filename
, 0);
17 printf("ERROR: open file: %s falied!\n", filename
);
21 file
= malloc(sizeof(*file
));
23 printf("malloc file structure error!\n");
35 uint32_t fstk_lseek(struct file
*file
, uint32_t off
, int mode
)
39 else if (mode
== SEEK_END
)
40 file
->offset
= file
->inode
->i_size
+ off
;
41 else if (mode
== SEEK_SET
)
48 int tfs_read(struct file
*file
, void *buf
, uint32_t count
)
50 struct tfs_sb_info
*sbi
= file
->sbi
;
51 int blocks
= roundup(count
, sbi
->s_block_size
);
52 int index
= file
->offset
>> sbi
->s_block_shift
;
53 int block
= file
->inode
->i_data
[index
++];
54 int bufoff
= file
->offset
& (sbi
->s_block_size
- 1);
61 if (file
->offset
>= file
->inode
->i_size
)
63 tfs_bread(sbi
, block
, buf
);
64 bytes_read
= sbi
->s_block_size
- bufoff
;
65 memcpy(buf
, buf
+ bufoff
, bytes_read
);
67 file
->offset
+= bytes_read
;
71 block
= file
->inode
->i_data
[index
++];
74 tfs_bread(sbi
, block
, buf
);
75 bytes_read
+= sbi
->s_block_size
;
76 file
->offset
+= sbi
->s_block_size
;
77 buf
+= sbi
->s_block_size
;
83 int tfs_write(struct file
*file
, void *buf
, uint32_t count
)
85 struct tfs_sb_info
*sbi
= file
->sbi
;
86 struct cache_struct
*cs
;
87 int blocks
= roundup(count
, sbi
->s_block_size
);
88 int index
= file
->offset
>> sbi
->s_block_shift
;
89 int block
= file
->inode
->i_data
[index
++];
90 int bufoff
= file
->offset
& (sbi
->s_block_size
- 1);
91 int bytes_written
= 0;
96 block
= tfs_alloc_block(sbi
, sbi
->s_data_area
);
98 printf("allocating block for new file faile! OUT OF SPACE!\n");
101 file
->inode
->i_data
[index
- 1] = block
;
103 cs
= get_cache_block(sbi
, block
);
104 bytes_written
= sbi
->s_block_size
- bufoff
;
105 memcpy(cs
->data
+ bufoff
, buf
, bytes_written
);
106 buf
+= bytes_written
;
107 file
->offset
+= bytes_written
;
108 /* write back to disk */
109 if (tfs_bwrite(sbi
, block
, cs
->data
) == -1) {
110 printf("disk I/O error:failed to write file data back to disk!\n");
116 block
= file
->inode
->i_data
[index
++];
118 block
= tfs_alloc_block(sbi
, sbi
->s_data_area
);
120 printf("allocating block for new file faile: out of space!\n");
123 file
->inode
->i_data
[index
- 1] = block
;
125 cs
= get_cache_block(sbi
, block
);
126 memcpy(cs
->data
, buf
, sbi
->s_block_size
);
127 bytes_written
+= sbi
->s_block_size
;
128 file
->offset
+= sbi
->s_block_size
;
129 buf
+= sbi
->s_block_size
;
130 if (tfs_bwrite(sbi
, block
, cs
->data
) == -1) {
131 printf("disk I/O error:failed to write file data back to disk!\n");
136 return bytes_written
;
139 void tfs_close(struct file
*file
)
142 free_inode(file
->inode
);