I want to open a new file and write a char array to it, but when I read back the contents of the file it has what I wrote to it followed by a bunch of garbage characters.
I want to map the file to memory, but when I read the file back from that map, I am getting those random characters following it.
...
char *towrite = "12345"
int fd = open("file.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
struct stat sb;
write(fd, &towrite, sizeof(towrite));
if(fstat(fd, &sb) != -1){
printf("file is %ld bytes long.\n", sb.st_size);
}
char *mappedfile = mmap(NULL, sb.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
for(int z=0; z < sb.st_size; z++){
printf("%c", mappedfile[z]);
}
printf("\n");
close(fd);
...
I've also noticed that the file size comes back as 1790 bytes which really doesn't seem right when I'm only writing a char array that is so small.
Forgive me for my insolence, I'm totally new to file reading and writing, as well as file mapping. I just can't seem to find what I am doing wrong with the documentation I've found online.
Thanks!