2011-03-31 68 views
2

我想從文件中的特定位置刪除字符串。是否有這樣做的功能? 我可以通過函數刪除文件的最後一行嗎?從文件中的特定位置刪除字符串

+1

什麼樣的字符串的僞C嗎?你必須指定。 – 2011-03-31 06:52:11

+1

聽起來是家庭作業 – 2011-03-31 06:54:50

+0

我不是學生 – Shweta 2011-03-31 07:00:16

回答

1

你有兩個選擇

  1. 要讀取整個文件,刪除你需要什麼,以及如果該文件是大回寫
  2. ,讀取文件的順序,刪除特定零件,以及向前後移動內容
+0

「之後轉移內容」如何? – Shweta 2011-03-31 07:01:10

+0

通過刪除內容後重寫部分 – 2011-03-31 07:59:39

2

不,沒有這樣的功能,可以讓你直接在文件上做到這一點。

您應該將文件內容加載到內存中並在那裏修改並回寫到文件。

1

我不喜歡找了所有的IO功能,所以在這裏有一個關於如何實現選項2 ArsenMkrt的回答

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)) 

大意的東西

相關問題