mmap和sprintf - c

时间:2017-02-18 02:43:49

标签: c printf mmap

我正在尝试将多个随机数写入内存,但我遇到的问题是for循环没有初始化所需的数字,我得到一个随机整数的输出,以及随机数的空格和新行

int random_range (unsigned const low, unsigned const high) {...}

/* Create and write to a shared file for communication with another process.
 *
 * argv[1] = file name
 *
 * Note: Error processing is omitted
 */
int main (int argc, char* const argv[]) {
  int fd;
  int* file_memory;
  int numOfInt;

  numOfInt = atoi(argv[2]); //Turning 2nd argument into an integer

  /* seed the random number generator */
  srand (time (NULL));

  /* open or create a file to hold an unsigned integer  */
  fd = open (argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

  /* write FILESIZE spaces */
  for (int i=0; i<FILESIZE; i++) write (fd, " ", 1);
  write (fd, "", 1); /* write a NULL at EOF */

  file_memory = mmap (NULL, FILESIZE, PROT_WRITE, MAP_SHARED, fd, 0);
  close (fd);

int* temp = file_memory;

  /* write a random integer to memory-mapped area  */
for(int x=0; x<numInt; ++x){
  if(x!=(numInt-1))
    sprintf((char*) file_memory++, "%d ", random_range (-100, 100));
  else
    sprintf((char*) file_memory++, "%d\n",random_range (-100, 100));
}

file_memory = temp;
  /* release the memory  */
  munmap (file_memory, FILESIZE);
}

0 个答案:

没有答案