2011-03-31 85 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)) 

大意的东西

相关问题