简体   繁体   English

文件I / O中的缓冲区大小

[英]Buffer size in file I/O

I'm trying to write a small program to find the buffer size of an open file stream. 我正在尝试编写一个小程序来查找打开文件流的缓冲区大小。 After searching around a little bit, I found the __fbufsize() function. 在搜索了一下之后,我找到了__fbufsize()函数。 This is the code I wrote: 这是我写的代码:

#include <stdio.h>
#include <stdio_ext.h>

void main() {
   FILE *f;
   int bufsize;

   f = fopen("test.txt","wb");
   if (f == NULL) {
      perror("fopen failed\n");
      return;
   }

   bufsize = __fbufsize(f);

   printf("The buffer size is %d\n",bufsize);

   return;
}

I get the buffer size as zero. 我得到缓冲区大小为零。 I'm a bit confused as to why this is happening. 我有点困惑为什么会发生这种情况。 Shouldn't the stream be buffered by default? 默认情况下不应该缓冲流吗? I get a non-zero value if I use setvbuf with _IOFBF before calling fbufsize. 如果在调用fbufsize之前将setvbuf与_IOFBF一起使用,则会得到一个非零值。

Note that the correct return type for main() is int , not void . 请注意, main()的正确返回类型是int ,而不是void

This code compiles on Linux (Ubuntu 14.04 derivative tested): 此代码在Linux上编译(Ubuntu 14.04衍生测试):

#include <stdio.h>
#include <stdio_ext.h>

int main(void)
{
    FILE *f;
    size_t bufsize;

    f = fopen("test.txt", "wb");
    if (f == NULL)
    {
        perror("fopen failed\n");
        return -1;
    }

    bufsize = __fbufsize(f);
    printf("The buffer size is %zd\n", bufsize);

    putc('\n', f);
    bufsize = __fbufsize(f);
    printf("The buffer size is %zd\n", bufsize);

    fclose(f);
    return 0;
}

When run, it produces: 运行时,它会产生:

The buffer size is 0
The buffer size is 4096

As suggested in the comments, until you use the file stream, the buffer size is not set. 正如评论中所建议的那样,在使用文件流之前,不会设置缓冲区大小。 Until then, you could change the size with setvbuf() , so the library doesn't set the buffer size until you try to use it. 在此之前,您可以使用setvbuf()更改大小,因此在您尝试使用它之前,库不会设置缓冲区大小。

The macro BUFSIZ defined in <stdio.h> is the default buffer size. <stdio.h>定义的宏BUFSIZ是默认缓冲区大小。 There's no standard way to find the buffer size set by setvbuf() . 找不到setvbuf()设置的缓冲区大小没有标准方法。 You need to identify the platform you're working on to allow useful commentary on __fbufsize() as a function (though it seems to be a GNU libc extension: __fbufsize() ). 您需要确定正在处理的平台,以便在__fbufsize()作为函数进行有用的注释(尽管它似乎是一个GNU libc扩展: __fbufsize() )。

There are numerous small improvements that should be made in the program, but they're not immediately germane. 应该在程序中进行许多小的改进,但它们并没有立即密切相关。

__fbufsize man page says: __fbufsize手册页说:

The __fbufsize() function returns the size of the buffer currently used by the given stream. __fbufsize()函数返回给定流当前使用的缓冲区的大小。

so I think this is buffer size used by the stream. 所以我认为这是流使用的缓冲区大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM