如何对文件I/O进行排序并更新现有文件 [英] How to sort file I/O and update existing file

查看:75
本文介绍了如何对文件I/O进行排序并更新现有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何按字母顺序对文本文件I/O进行排序?

How do I sort a text file I/O in alphabetical order?

推荐答案

如果文本文件很小,则可以将每一行读入内存,应用进行排序,然后将它们全部按排序顺序写回到同一文件.

如果文本文件很大,则可以对文本文件中的行进行排序,而不会一次将两个以上的行加载到内存中.从第一行开始,将其读入,并将其称为当前"行.接下来,将其与文件中的第二行进行比较.如果它们的顺序不正确,请交换它们,然后将文本文件中的前一行用作当前"行(如果到达文件的开头,只需从文件的第一行开始重新应用相同的算法).如果行匹配,请移至文件的下一行,并使其成为当前"行.继续此过程,直到到达文件末尾.

可以使用更快的方式对文本文件进行排序,但这是我可以向您描述的最简单的方法.
If the text file is small, you can read each line into memory, apply a sort on the lines, then write them all back to the same file in their sorted order.

If a large text file, you can sort the lines in the text file without loading more than 2 into memory at once. Start with the first line, read it in, and call this the "current" line. Next, compare it to the second line in the file. If they are not in the correct order, swap them, then use the previous line in the text file as the "current" line (if you reach the beginning of the file, just reapply the same algorithm starting from the first line in the file). If the lines match, move on to the next line in the file and make that the "current" line. Continue this procedure until you''ve reached the end of the file.

There are faster ways of sorting text files, but that is the simplest way I could describe it to you.


这篇关于如何对文件I/O进行排序并更新现有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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