I’m trying to remove white spaces contained in a file and after I’ve read it using mmap, I proceed by removing white spaces by using a for-loop and shirting the next pointer to the current index but it doesnt seem to work. Here’s my code to illustrate:
static unsigned long get_size_by_fd(int fd) {
struct stat statbuf;
if(fstat(fd, &statbuf) < 0) exit(-1);
return statbuf.st_size;
}
fd = open("/home/text.txt", O_RDONLY);
file_size = get_size_by_fd(fd);
fb = mmap(0, file_size, PROT_READ || PROT_WRITE, MAP_SHARED, fd, 0);
for (i = 0; i<file_size; i++) {
if (fb[i] == 0x20) {
fb[i] = fb[i++];
}
}
There is no sequence point in the assignment
fb[i] = fb[i++];so you get unspecified results. Better to write it plainly:I also added an additional bounds check (consider when there are spaces at the end).
Note that your program makes assumptions on the file encoding.