写空文件不写文件,写太大文件写空文件

时间:2019-04-02 09:26:46

标签: c memcpy fuse

我正在为FUSE程序编写文件操作。但是,我在使用file_operations.write函数时遇到了一些麻烦。我遇到的问题是:

  • 试图写入一个空文件(在vim中打开并立即保存,因此写为0L 0C),它根本不会写入,并且内容保持不变,因此,如果该文件先前包含“文本”,则仍将包含“文本”。
  • 尝试写入大文件(大约10KB)将导致文件为空。

对于空文件部分。我已经尝试了几种方法,例如检查大小是否小于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(对我来说最有意义)将重新分配为大小为0 + 1(空字节为1)的char *
  • 然后将文件指向内容>
  • 然后将0字节从缓冲区复制到file-> contents
  • 在文件->内容的末尾写一个'\0'字符(大小为length of the realloc'ed block - 1);在这种情况下,将'\0'写入第0个索引。
  • 返回写入的大小,在这种情况下为0。

但是,vim会关闭报告已将0L 0C写入文件,但该文件未触及。

大文件:

  • 该函数将多次调用write以将大块数据写入文件中
  • 但是会写入一个空文件。

1 个答案:

答案 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;
}
相关问题