Reputation: 15
I'm writing a simple C program for reversing bytes in a file (just for learning purposes). I'm opening my file, map it into the memory and reverse the bytes order. So the first one becomes last, the last becomes first and so on.
In memory everything works fine (checked it with gdb) however when I sync and unmap memory the file on drive doesn't get changed (the bytes are in the same order, not reversed).
The worst part is that I get no error while running the program.
And of course I'm the owner of the file and it's readable and writable for me.
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
int main (int argc, char *argv[]){
int fd_in;
int i, j;
char tmp;
struct stat inode;
char *addr_in;
if(argc < 2){
printf("Usage: %s input\n", argv[0]);
return -1;
}
fd_in = open(argv[1], O_RDWR);
if(fd_in == -1){
perror("Error opening file");
return 2;
}
if(fstat(fd_in, &inode)){
perror("fstat error");
}
addr_in = mmap(NULL, inode.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd_in, 0);
if(addr_in == (char*)(-1)){
perror("Error mapping memory");
close(fd_in);
return 2;
}
for(i = 0, j = inode.st_size-1; i < inode.st_size ; i++, j--){
tmp = addr_in[i];
addr_in[i] = addr_in[j];
addr_in[j] = tmp;
}
if(msync(addr_in, inode.st_size, MS_SYNC) == -1){
perror("sync error");
return 2;
}
if(munmap(addr_in, inode.st_size) == -1){
perror("unmap error");
return 2;
}
close(fd_in);
}
Upvotes: 1
Views: 565
Reputation:
for(i = 0, j = inode.st_size-1; i < inode.st_size ; i++, j--)
should be
for(i = 0, j = inode.st_size - 1; i < inode.st_size / 2; i++, j--)
If you go along the entire array, you'll reverse it twice, i. e. essentially nothing will happen.
Upvotes: 1