C语言删除文件中的一行 [英] Delete a Line from a file in C Language

查看:41
本文介绍了C语言删除文件中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除文件中的某些行,并根据行的某些部分是否与指定的字符串匹配,在同一文件中插入某些行.有没有办法在不使用临时文件将内容复制到等等的情况下做到这一点?

I want to delete certain lines in a file and insert certain lines in the same file based on whether certain parts of the line match a specified string. Is there a way of doing this without using a temporary file to copy the contents to and so on?

推荐答案

问题是,文件(本质上)是磁盘上的字节数组(或任何其他物理基板,但无论如何都是字节!),并且一行" 可以采用不同数量的字节;所以要插入或删除行(除非你总是严格地用另一行以字节为单位的长度完全相同的行替换一行)需要通过字节差异向上"或向下"移动"文件的所有其余部分...这可能是一项极其繁重的操作(因为文件的其余部分可能是千兆字节,即使您只是将一行的长度向文件开头更改 1 个字节).

Problem is, a file is (essentially) an array of bytes on disk (or whatever other physical substrate, but, bytes anyway!), and "a line" can take a varying number of bytes; so to insert or remove lines (unless you're always rigorously replacing a line with another line of exactly the same length in bytes) would require "shifting" all the rest of the file "up" or "down" by the difference in bytes... which can be an extremely onerous operation (as the rest of the file can be gigabytes even if you're just changing one line's length by 1 byte towards the beginning of the file).

因此,此类操作可能非常繁重,因此通常不会在任何支持具有可变行长的语言(C、Python、Java、C++、Ruby 或任何其他此类语言)的文件中作为原语提供.您真的不太可能真的需要在性能和风险方面付出如此巨大的潜在成本(在 GB移位"或数据上移或下移期间系统或磁盘崩溃可能会破坏整个大文件的可用性),当您试图避免的非常简单、足够、快速、安全且合理的技术基本上具有零缺点(因此,您为什么要避免它远非显而易见?).

So, such operations can be incredibly onerous and therefore are typically never offered as primitives in ANY language supporting files with variable line length (C, Python, Java, C++, Ruby, or ANY other such language). It's extremely unlikely that you really need to pay such a potentially unbound cost in performance AND risk (a system or disk crash during the "shift" of GB or data up or down can destroy the usabilty of your whole, huge file), when the perfectly simple, adequate, fast, safe, and reasonable technique you're trying to avoid has basically ZERO downsides (so it's far from obvious WHY are you trying to avoid it?).

使用与源文件不同的结果文件,完成后将结果文件覆盖在源文件上(如果您在同一文件系统中,则在大多数系统上是原子操作),并且您确实拥有所有可能的世界中最好的.

Use a result-file different from the source-file, when done mv the result-file over the source-file (an atomic operation on most systems if you're within the same filesystem), and you really do have the best of all possible worlds.

这篇关于C语言删除文件中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆