1

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

Groosha
  • 2,897
  • 2
  • 22
  • 38
  • 1
    `fopen` the file an `fread` bytes. – ouah Mar 22 '14 at 12:11
  • 1
    sorry just read that you want to do that fro C. You can invoke the dd from C: "dd if=/dev/urandom of="sample.txt bs=100M count=1"" with system or fork – Marco A. Mar 22 '14 at 12:12
  • If you don't want to use `dd`, look for the source of any file-copying program (there are plenty of those), then modify it to stop after it has copied a certain amount of bytes. – Guntram Blohm Mar 22 '14 at 12:13

1 Answers1

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:

  1. 3 = open() /dev/urandom
  2. 4 = open() target file
  3. read() in a buffer from 3 and write into 4 until written size equals 100*1024*1024
  4. close(3)
  5. close(4)

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

Aif
  • 11,015
  • 1
  • 30
  • 44
  • What is 3 and 4? File descriptors? Could you please explain with just a little of code? – Groosha Mar 22 '14 at 12:18
  • 1
    Yeah 3 and 4 are file descriptors returned by `open()`, used to read / write and close. – Aif Mar 22 '14 at 12:21
  • And last question: how big should be buffer? I'm quite a noob, so I think, that 1 megabyte of buffer is normal. Is it right? Or I must use much smaller one? – Groosha Mar 22 '14 at 12:25
  • 1
    I think above psudo code implemented partially here http://stackoverflow.com/questions/2572366/how-to-use-dev-random-or-urandom-in-c – Jayesh Bhoi Mar 22 '14 at 12:28
  • You should avoid a big buffer, because I would consume a lot of memory for that process. I think 100k buffer is a fair trade. – Aif Mar 22 '14 at 13:01