如何用/ dev / urandom中的100 mb数据填充文件? [重复]

时间:2023-01-24 09:40:59

This question already has an answer here:

这个问题在这里已有答案:

I'm new to Linux system programming.
How can I fill some file with 100 mb of any data (but not zeros)?
The only way I see is to use /dev/urandom, but how to do this?
I know there's dd command in Shell, but I'm writing a C program

我是Linux系统编程的新手。如何用100 mb的任何数据(但不是零)填充一些文件?我看到的唯一方法是使用/ dev / urandom,但是如何做到这一点?我知道Shell中有dd命令,但我正在写一个C程序

1 个解决方案

#1


1  

read(2) system call will fill a buffer buf with at most count bytes, and return the actual size that was filled. So what you need to do is just:

read(2)系统调用将填充最多count个字节的缓冲区buf,并返回填充的实际大小。所以你需要做的只是:

  1. 3 = open() /dev/urandom
  2. 3 = open()/ dev / urandom

  3. 4 = open() target file
  4. 4 = open()目标文件

  5. read() in a buffer from 3 and write into 4 until written size equals 100*1024*1024
  6. read()在3的缓冲区中写入4,直到写入的大小等于100 * 1024 * 1024

  7. close(3)
  8. close(4)

and you're done. You can also optimize using mmap() for instance, but it may not worth it.

你已经完成了您也可以使用mmap()进行优化,但它可能不值得。

#1


1  

read(2) system call will fill a buffer buf with at most count bytes, and return the actual size that was filled. So what you need to do is just:

read(2)系统调用将填充最多count个字节的缓冲区buf,并返回填充的实际大小。所以你需要做的只是:

  1. 3 = open() /dev/urandom
  2. 3 = open()/ dev / urandom

  3. 4 = open() target file
  4. 4 = open()目标文件

  5. read() in a buffer from 3 and write into 4 until written size equals 100*1024*1024
  6. read()在3的缓冲区中写入4,直到写入的大小等于100 * 1024 * 1024

  7. close(3)
  8. close(4)

and you're done. You can also optimize using mmap() for instance, but it may not worth it.

你已经完成了您也可以使用mmap()进行优化,但它可能不值得。