C语言中的文件处理-从文本文件列表中删除特定单词 [英] File Handling in C - Removing specific words from a list in text file

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

问题描述

我正在使用以下代码从基本C程序中填充一个简短的字典:

I am populating a short dictionary from my basic C program using the following code :

void main () {

FILE *fp;

fp = fopen("c:\\CTEMP\\Dictionary2.txt", "w+"); 

fprintf(fp, Word to Dictionary");

但是,我也希望删除某些我不想再出现在词典中的单词.我做了一些研究,我知道

However I would also wish to remove certain words which I do not longer wish to be in the dictionary. I did some research and I know that

"您不能从文件中删除内容,而将剩余的内容下移.您只能追加,截断或覆盖.

" You can't remove content from a file and have the remaining content shifted down. You can only append, truncate or overwrite.

您最好的选择是将文件读入内存,在内存中进行处理,然后再写回磁盘"

Your best option is to read the file in to memory, process it in memory and then write it back to disk"

如何创建没有要删除的单词的新文件?

How can I create a new file without the word I want to remove ?

谢谢

推荐答案

  • 您打开两个文件:一个(用于读取)文件和一个新(用于读取文件). 写作).
  • 您循环浏览第一个文件,依次读取每一行.
  • 您将每一行的内容与您需要的单词进行比较 删除.
  • 如果该行与任何删除词都不匹配,则 您将其写入新文件.
    • You open two files: the one you've got (for reading) and a new one (for writing).
    • You loop through the first file reading each line in turn.
    • You compare the contents of each line with the words you need to delete.
    • If the line does not match any of the deletion words, then you write it to the new file.
    • 如果您需要进行的操作复杂得多,则可以使用mmap()从字面上将其读入内存",但这是一种更高级的技术;您需要将文件视为不带零终止符的字节数组,并且有很多方法可以解决这个问题.

      If the manipulation that you need to do is much more complex then you can literally "read it into memory" using mmap(), but that is a more advanced technique; you need to treat the file as a byte array with no zero terminator and there are lots of ways to mess that up.

      这篇关于C语言中的文件处理-从文本文件列表中删除特定单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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