I want to delete a string from a particular position in the file. Is thre a function to do that? Can I delete last line of a file through a function?
3 Answers
You have two option
- To read whole file, remove what you need and write it back
- If the file is big, read file sequentially, remove given part, and move content after that forward
2 Comments
Shweta
"move content after that forward" How?
Arsen Mkrtchyan
By rewriting part after removed content
I don't feel like looking up all the io functions, so here's pseudo-c on how to implement option 2 of ArsenMkrt's answer
char buffer[N]; // N >= 1
int str_start_pos = starting position of the string to remove
int str_end_pos = ending position of the string to remove
int file_size = the size of the file in bytes
int copy_to = str_start_pos
int copy_from = str_end_pos + 1
while(copy_from < file_size){
set_file_pos(file, copy_from)
int bytes_read = read(buffer, N, file)
copy_from += bytes_read
set_file_pos(file, copy_to)
write(buffer, file, bytes_read)
copy_to += bytes_read
}
truncate_file(file,file_size - (str_end_pos - str_start_pos + 1))
something to that effect