Im trying to remove string from file by seeking its position then remove. I dont want to store the entity file in a string than replace. I need to replace it directy on the file, is there any way I could do this?
I have to find the "#" then remove until I find the next.
Example: Remove #2 data from myfile.txt
#1|info1|info2|info3|#2|inf11|info12|inf22|#3|inf11|info12|inf22|
After remove:
#1|info1|info2|info3|#3|inf11|info12|inf22
How can I do this?
PHP doesn't provide any way to directly manipulate file contents. You have to read into a PHP variable, then write back out to the file.
In C on a POSIX system you can do it using mmap()
.
int fd = open("myfile.txt", O_RDWR);
struct stat stat_buf;
fstat(fd, &stat_buf);
size_t len = stat_buf.st_size;
char *contents = mmap(NULL, len, PROT_WRITE, MAP_SHARED, fd, 0);
char *num2 = strstr(contents, "#2"); // Find #2
char *num3 = strstr(num2, "#3"); // Find #3 after #2
memmove(num3, num2, len-(num3-contents)); // Shift everything from #3 over
memset(contents + len - (num3 - num2), num3 - num2); // Zero the end of the file
close(fd);