如何在文件中附加特定数量的空字节?[关闭]


26

我有一个写一些文件的脚本,但是我需要一个特定的大小。因此,我想知道是否存在通过使用标准命令行工具(例如,通过从复制/dev/zero)将特定数量的空字节附加到文件的方法?


1
这个问题似乎离题,因为它与编程有关,属于Stack Overflow
珍妮D说恢复莫妮卡

oflag=append对你有用吗?
Mark K Cowan 2014年

澄清@Mark K Cowan的评论;他指的是dd命令。
亚历山大·波兹涅夫

仅供参考,似乎fallocate是在文件中插入孔的另一种选择。superuser.com/a/1172904/111432
akostadinov

Answers:


41

truncate比快得多dd。要以10个字节增长文件,请使用:

 truncate -s +10 file.txt 

2
它要快得多,因为它将生成一个稀疏文件,这是您大多数时候想要的-但是,如果您不希望稀疏文件,则dd方法将起作用。
derobert

34

您也可以尝试

dd if=/dev/zero bs=1 count=NUMBER >> yourfile

这将从/ dev / zero读取,并附加到yourfile NUMBER个字节中。


7

下面是仅使用dd将10MB附加到文件的示例。

[root@rhel ~]# cp /etc/motd ./test
[root@rhel ~]# hexdump -C test |tail -5
000003e0  0a 0a 3d 3d 3d 3d 3e 20  54 65 78 74 20 6f 66 20  |..====> Text of |
000003f0  74 68 69 73 20 6d 65 73  73 61 67 65 20 69 73 20  |this message is |
00000400  69 6e 20 2f 65 74 63 2f  6d 6f 74 64 20 3c 3d 3d  |in /etc/motd <==|
00000410  3d 3d 0a                                          |==.|
00000413

[root@rhel ~]# dd if=/dev/zero of=/root/test ibs=1M count=10 obs=1M oflag=append conv=notrunc
10+0 records in
10+0 records out
10485760 bytes (10 MB) copied, 0.0208541 s, 503 MB/s

[root@rhel ~]# hexdump -C test |tail -5
00000410  3d 3d 0a 00 00 00 00 00  00 00 00 00 00 00 00 00  |==..............|
00000420  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
*
00a00410  00 00 00                                          |...|
00a00413

5

我的第一个猜测是:

dd if=/dev/zero of=myfile bs=1 count=nb_of_bytes seek=$(stat -c%s myfile)

基本上,此命令告诉dd在文件末尾“执行”并添加先前从/ dev / zero读取的一些字节。

问候,


2
cat "your file" /dev/zero | head -c "total number of bytes"

要么

head -c "number of bytes to add" /dev/zero >> "your_file"

并更轻松地计算尺寸:

head -c $(( "total number of bytes" - $(stat -c "%s" "your_file") )) /dev/zero >> "your_file"

0

如果用空字节填充文件,我猜是char *在C 中操作文件。如果是这种情况,则可能不需要用空字节填充文件,只在末尾添加一个空字节即可。文件,然后用随机字节填充就足够了。在这种情况下,C程序将非常高效(仅可用于小于第二个参数的文件,否则数据将被覆盖)。它甚至可以做您想做的事情(用空字节填充),因为lseek函数定义指出:

lseek()函数应允许设置文件偏移量,使其超出文件中现有数据的末尾。如果此时稍后再写入数据,则随后在间隙中读取数据将返回值为0的字节,直到将数据实际写入间隙中为止。

在这种情况下,对lseek和的第一个调用write可以删除。但是测试应该在您的系统上进行第一...

#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

/* 1st parameter: a file name, 2nd parameter: a file size. */
int main(int argc, char ** args) {
   int nfd = open(args[1], O_WRONLY);
   lseek(nfd, 0, SEEK_END);
   write(nfd, "\0", 1);
   lseek(nfd, atoi(args[2]) - 1, SEEK_SET);
   write(nfd, "\0", 1);
   close(nfd);
   return 0;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.