Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SPIFFS_ftruncate function #278

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/spiffs.h
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,15 @@ s32_t SPIFFS_remove(spiffs *fs, const char *path);
*/
s32_t SPIFFS_fremove(spiffs *fs, spiffs_file fh);

/**
* Truncates a file at given size
* @param fs the file system struct
* @param fh the filehandle of the file to truncate
* @param new_size the new size, must be less than existing file size
* @retval s32_t error code
*/
s32_t SPIFFS_ftruncate(spiffs* fs, spiffs_file fh, u32_t new_size);

/**
* Gets file status by path
* @param fs the file system struct
Expand Down
39 changes: 39 additions & 0 deletions src/spiffs_hydrogen.c
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,45 @@ s32_t SPIFFS_fremove(spiffs *fs, spiffs_file fh) {
#endif // SPIFFS_READ_ONLY
}

s32_t SPIFFS_ftruncate(spiffs* fs, spiffs_file fh, u32_t new_size) {
#if SPIFFS_READ_ONLY
(void)fs; (void)fh; (void)new_size;
return SPIFFS_ERR_RO_NOT_IMPL;
#else
SPIFFS_API_CHECK_CFG(fs);
SPIFFS_API_CHECK_MOUNT(fs);
SPIFFS_LOCK(fs);

spiffs_fd* fd;

fh = SPIFFS_FH_UNOFFS(fs, fh);
s32_t res = spiffs_fd_get(fs, fh, &fd);
SPIFFS_API_CHECK_RES_UNLOCK(fs, res);

if ((fd->flags & SPIFFS_O_WRONLY) == 0) {
res = SPIFFS_ERR_NOT_WRITABLE;
SPIFFS_API_CHECK_RES_UNLOCK(fs, res);
}

#if SPIFFS_CACHE_WR
spiffs_fflush_cache(fs, fh);
#endif

s32_t file_size = (fd->size == SPIFFS_UNDEFINED_LEN) ? 0 : fd->size;
if (new_size == file_size) {
res = SPIFFS_OK;
} else if (new_size > file_size) {
res = SPIFFS_ERR_END_OF_OBJECT; // Same error we'd get from SPIFFS_lseek
} else {
res = spiffs_object_truncate(fd, new_size, 0);
}
SPIFFS_API_CHECK_RES_UNLOCK(fs, res);

SPIFFS_UNLOCK(fs);
return SPIFFS_OK;
#endif
}

static s32_t spiffs_stat_pix(spiffs *fs, spiffs_page_ix pix, spiffs_file fh, spiffs_stat *s) {
(void)fh;
spiffs_page_object_ix_header objix_hdr;
Expand Down
1 change: 1 addition & 0 deletions src/spiffs_nucleus.c
Original file line number Diff line number Diff line change
Expand Up @@ -1019,6 +1019,7 @@ s32_t spiffs_object_update_index_hdr(
// change name
if (name) {
strncpy((char*)objix_hdr->name, (const char*)name, SPIFFS_OBJ_NAME_LEN);
objix_hdr->name[SPIFFS_OBJ_NAME_LEN - 1] = '\0';
}
#if SPIFFS_OBJ_META_LEN
if (meta) {
Expand Down