I've been struggling with this one for a while, and I can't quite figure it out!
I've created an mmap-write.c script that properly maps a file of integers into memory. For example, when I run:
./mmap-write /tmp/afile 10
I can then cat the file and get something similar to the following:
cat /tmp/afile
71 -94 -92 -18 58 63 -16 97 47 -55
In other words, my mmap-write script creates 10 random ints and maps them to memory. Now, in my mmap-read script, I'm having difficulty reading the ints back to the console, and I get the following output:
71 1 -94 -94 94 4 -92 -92 92 2
You can see how it's reading the ints in order, but printing the first int, and reprinting it, eliminating the first character, until it hits the end. Then it starts doing the same with the next integer in the file.
Anyway, here's my code:
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
#include "mmap.h"
int main (int argc, char* const argv[]) {
int fd, i, integer, numInts;
char* file_memory;
numInts = atoi(argv[2]);
fd = open (argv[1], O_RDWR, S_IRUSR | S_IWUSR);
memset(file_memory, '\0', FILESIZE);
file_memory = (char*) mmap (NULL, FILESIZE, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
close (fd);
for (i = 0; i < numInts; i++) {
sscanf((char*) &file_memory[i], "%d ", &integer);
printf ("%d ", integer);
}
munmap (file_memory, FILESIZE);
return 0;
}
PLEASE NOTE: I do have error checking in my actual code, but I've left it out for brevity, and clarity, since I don't believe it's the actual culprit here. I'm pretty confident this is the offending snippet:
for (i = 0; i < numInts; i++) {
sscanf((char*) &file_memory[i], "%d ", &integer);
printf ("%d ", integer);
}
Any assistance would be greatly appreciated!