我正在为FUSE程序编写文件操作。但是,我在使用file_operations.write
函数时遇到了一些麻烦。我遇到的问题是:
对于空文件部分。我已经尝试了几种方法,例如检查大小是否小于1(我假设这是写入空文件时的大小),并简单地将char*
指向单个'\0'
字节。
我还尝试了区分大小写的情况,但由于某种奇怪的原因,发现大小为-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写入文件,但该文件未触及。
大文件:
答案 0 :(得分:1)
我不习惯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;
}