我正在为FUSE程序编写文件操作。但是我在使用file_operations.write
功能时遇到了一些麻烦。我遇到的问题是:
对于空文件部分。我已经尝试过几个方面,例如检查大小是否小于1(我假设是写入空文件时给出的大小),并简单地将char*
指向单个'\0'
字节。
我也试过单独的if情况,并且由于某些奇怪的原因发现大小为-2,但是当我尝试写一个空文件时,如上所述,当找到-2时,它仍然无效。
对于文件太大,我不知道。
static int fs_write(const char* path, const char* buffer, size_t size, off_t offset, struct fuse_file_info* ffinfo) {
// Find the associated file_t* and dir_t* to the file.
file_t* file = get_file_from_path(path);
dir_t* directories = get_parents_from_path(path);
// The contents of a file are stored in a char* so I have to realloc
// the previous pointer and memcpy the new contents from buffer to
// file->contents, using size and offset as an indication of how large
// to make the realloc and what to copy over.
char* file_contents_new = (char*) realloc(file->contents, (size + 1) * sizeof(char));
// realloc failed
if (file_contents_new == NULL)
return -ENOMEM;
// point the previous file contents pointer to the newly allocated section.
file->contents = file_contents_new;
// Copy from buffer+offset to the file contents with the size provided.
memcpy(file->contents, buffer + offset, size);
*(file->contents + size) = '\0'; // Append NULL char to end file string.
return size;
}
在这里,我希望能够正确处理空文件和大文件,因为:
'\0'
字符到文件结尾 - >内容(大小,这是length of the realloc'ed block - 1
);在这种情况下,将'\0'
写在第0个索引处。但是,vim关闭报告它已将0L 0C写入文件,但该文件未被触及。
大文件:
我不习惯使用FUSE,但我认为你不能很好地使用这些参数(参见https://github.com/libfuse/libfuse/blob/master/example/passthrough.c)
buffer
:要写的数据size
:缓冲区的大小offset
:写入文件的位置。所以你的代码看起来像:
static int fs_write(const char* path, const char* buffer, size_t size, off_t offset, struct fuse_file_info* ffinfo)
{
// Find the associated file_t* and dir_t* to the file.
file_t* file = get_file_from_path(path);
dir_t* directories = get_parents_from_path(path);
/* realloc to store data. Note the +1 to store the final \0 */
char* file_contents_new = realloc(file->contents, file->size + size+1);
// realloc failed
if (file_contents_new == NULL)
return -ENOMEM;
// point the previous file contents pointer to the newly allocated section.
file->contents = file_contents_new;
/* update size too, without to +1 to prevent adding one at each write call */
file->size = file->size + size;
// Copy buffer to the file taking offset into account
memcpy(file->contents + offset, buffer, size);
/* Append NULL char to end file string. */
*(file->contents + file->size) = '\0';
return size;
}