hi there,
i try to map a file in memory, in linux, using mmap, so that what i write in memory will be written in the file as well.

the piece of code looks like this

fd = open(argv[1], O_RDWR);
	if (fd == -1) {
		error_message(__FILE__, __LINE__, "'open' failed ");
		return 1;
	}
	
	// find out the size of the file in bytes
	// we need the size, because we cannot write past the end of the file
	// so, we need to make sure not to write at an offset larger than 'info.st_size'
	if (fstat(fd, &info) == -1) {
		error_message(__FILE__, __LINE__, "'fstat' failed ");
		return 1;
	}
	
	printf("The file has %ld bytes\n", info.st_size);
	if (info.st_size == 0) {
		fprintf(stderr, "We cannot map a file with size 0\n");
		return 0;
	}
	
	
	// TODO
	mapping = mmap(NULL, info.st_size, PROT_WRITE, MAP_PRIVATE, fd, 0);
	if (mapping == MAP_FAILED) {
		perror("mmap:");
		return -1;
	}
	else fprintf(stderr, "Successful mapping at the address %p\n", mapping);
	
	memcpy(mapping, "hello", 5);
	
	if (msync(mapping, info.st_size, MS_SYNC) == -1) {
		perror("msync:");
		return -1;
	}	
	
	// close the file
	if (close(fd) == -1) {
		error_message(__FILE__, __LINE__, "'close' failed ");
		return 1;
	}

i don't realy know how this works, but i think msync should update the file with the contents from memory.

what is wrong with the code?

nevermind... i just found that the program was actually working... :D but the changes i made were not visible unless i closed the file, and opened again. i don't know why this happens. if i change the file in another editor, and save it, i'm announced that the contents were changed outside the program, but if i modify the file using mmap it doesn't say anything

This question has already been answered. Start a new discussion instead.