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

问题描述 投票:0回答:1

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

  • 试图写一个空文件(在vim中打开并立即保存,所以它写的是0L 0C)它根本不写,并保持内容不变,所以如果文件以前包含“text”,它仍然会包含“text” 。
  • 尝试写一个大文件(大约10KB)将导致一个空文件。

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

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

大文件:

  • 该函数将多次调用write以块的形式写入文件
  • 但是会写入一个空文件。
c memcpy fuse
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.