简体   繁体   English

从C中的文件删除字符

[英]Delete a character from a file in C

How can I delete few characters from a file using C program? 如何使用C程序从文件中删除几个字符?

I could not find any predefined functions for it. 我找不到任何预定义的函数。

To understand the purpose, I am trying to send a file through a socket, if N bytes are sent successfully, I want to delete those bytes from the file. 为了理解目的,我试图通过套接字发送文件,如果成功发送了N个字节,我想从文件中删除那些字节。 At the end, the file will be empty. 最后,该文件将为空。 Any other way to do this efficiently? 还有其他有效方法吗?

Thanks Pradeep 感谢Pradeep

If they're at the end, truncate the file at the appropriate length. 如果它们在末尾,则以适当的长度截断文件。 If they're not then you'll need to rewrite the file. 如果不是,则需要重写该文件。

Your way is pretty inefficient for large files, since you would have to copy "the rest of the file" some bytes further to the beginning, which costs much. 对于大型文件,您的方式效率很低,因为您必须将“文件的其余部分”复制到开头一些字节,这会花费很多。 I would rather record the "current sending position" somewhere outside of the file and update that information. 我宁愿将“当前发送位置”记录在文件之外的某个位置并更新该信息。 That way, you don't have to copy the rest of the file so often. 这样,您不必如此频繁地复制文件的其余部分。

There is no straightforward way to delete bytes from the beginning of a file. 没有直接的方法可以从文件开头删除字节。 You will have to start from where you want to trim the file, and read from there to the end of the file, writing to the start of the file. 您将必须从要修剪文件的位置开始,然后从此处读取到文件的末尾,然后写入文件的开头。

It might make more sense to just track how many bytes you have already written to the file in some other file. 仅跟踪已在其他文件中写入多少个字节的字节可能更有意义。

you should use an index which points to the beginning of the data you haven't sent yet. 您应该使用一个索引,指向尚未发送的数据的开头。 It is not necessary to delete what you have sent, just pass them, when you send the whole file delete it. 发送整个文件时,不必删除已发送的内容,只需传递它们即可。

如果字符是一个接一个的字符,那么为什么不尝试fseek();?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM