简体   繁体   English

如何检查是否可以创建给定长度的文件?

[英]How to check if a file of given length can be created?

I want to create a non-sparse file of a given length (ie 2GB), but I want to check if that is possible before actually writing stuff to disk. 我想创建一个给定长度(即2GB)的非稀疏文件,但我想在实际将内容写入磁盘之前检查是否可行。

In other words I want to avoid getting ENOSPC (No space left on device) while writing. 换句话说,我想避免在写入时获得ENOSPC (设备上没有剩余空间)。 I'd prefer not to create a "test file" of size 2GB or things like that just to check that there is enough space left. 我不想创建一个大小为2GB的“测试文件”或类似的东西,只是为了检查是否有足够的空间。

Is that possible? 那可能吗?

Use posix_fallocate(3) . 使用posix_fallocate(3)

From the description: 从描述:

The function posix_fallocate() ensures that disk space is allocated for the file referred to by the descriptor fd for the bytes in the range starting at offset and continuing for len bytes. 函数posix_fallocate()确保为描述符fd引用的文件分配磁盘空间,该文件用于从offset开始并继续len字节的范围内的字节。 After a successful call to posix_fallocate(), subsequent writes to bytes in the specified range are guaranteed not to fail because of lack of disk space 在成功调用posix_fallocate()之后,由于缺少磁盘空间,后续写入指定范围内的字节将保证不会失败

You can use the statvfs function to determine how much free bytes (and inodes) a given filesystem has. 您可以使用statvfs函数来确定给定文件系统有多少空闲字节(和inode)。

That should be enough for a quick check, but do remember that it's not a guarantee that you'll be able to write as much (or, for that matter, that writing more than that would have failed) - other applications could also be writing to (or deleting from) the same filesystem. 这应该足以进行快速检查,但要记住,这并不能保证你能够写得那么多(或者,就此而言,写作不会失败) - 其他应用程序也可以写作到(或删除)相同的文件系统。 So do continue to check for various write errors. 所以继续检查各种写入错误。

fallocate or posix_fallocate can be used to allocate (and deallocate) a large chunk. fallocateposix_fallocate可用于分配(和解除分配)大块。 Probably a better option for your use-case. 对于您的用例可能是更好的选择。 (Check the man page, there's a lot of options for space management that you might find interesting.) (查看手册页,您可能会发现很多有趣的空间管理选项。)

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

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