Shweta
Shweta

Reputation: 5456

deleting a string from a particular position in a file

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?

Upvotes: 2

Views: 3222

Answers (3)

Bwmat
Bwmat

Reputation: 4694

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

Upvotes: 1

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50752

You have two option

  1. To read whole file, remove what you need and write it back
  2. If the file is big, read file sequentially, remove given part, and move content after that forward

Upvotes: 2

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22124

No there is no such function that will let you do this directly on a file.

You should load up the file content in memory and modify there and write back to file.

Upvotes: 2

Related Questions