请问 如何修改文本文件的最后一行内容?
我有一文本文件,例如:
A B
C D
E F
我现在想把最后一行E F 改成 1 2,
A B
C D
1 2
请问怎么实现?
如果不能直接修改,我想先删除最后一行
A B
C D
然后再追加 1 2
A B
C D
1 2
这样又怎么实现呢?
------解决方案--------------------先算出你文体有多少行,这需要你先读一遍文本,然后再读一遍,到最后一行的时候做替换
或者还有一种方法,用两个游标(c++里叫指针)一个用来记录前面的,另一个用来记录后面的,如果前面的走到文本的结尾了,那就把后面的替换了
------解决方案-------------------- '应该与查找替换差不多吧!
Option Explicit
Private Sub Command1_Click()
Call ReplaceInFile( "C:\test.txt ", "x ", "10000 ")
End Sub
Private Sub ReplaceInFile(FileName As String, ReplaceStr As String, ReplaceWithStr As String)
Dim FileNum As Long, strFileContent As String, strTemp As String
FileNum = FreeFile
If Dir(FileName) <> " " Then
Open FileName For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, strTemp
strFileContent = strFileContent & strTemp & vbCrLf
Wend
Close #FileNum
strFileContent = Replace(strFileContent, ReplaceStr, ReplaceWithStr, , , vbDatabaseCompare)
Open FileName For Output As #FileNum
Print #FileNum, strFileContent
Close #FileNum
End If
End Sub
------解决方案--------------------如果文件很大(几百M以上),就指定一个data buffer,然后一块一块读,直到吃到最后一块,记录最后一行开始处到EOF的offset,sw.basestream.seek(offset. seekorigin.end);// sw is a StreamWriter object;开始替换,然后sw.flush;
如果文件不大,直接readtoend,然后回写
------解决方案--------------------如果文件很大(几百M以上),就用FileStream打开二进制方式读写,
指定一个data buffer,然后seek到倒数第一块,一块一块读,直到找到最后一个回车换行的位置,seek到此位置,写入即可~
------解决方案--------------------private void button1_Click(object sender, EventArgs e)
{
FileStream vFileStream = new FileStream(@ "c:\temp\temp.log ",
FileMode.Open, FileAccess.ReadWrite);
byte[] vBuffer = new byte[0x1000];
int vReadLength;
int vReadCount = 0;
bool vLineEnd = false;
int j = 0;
string vText = "Zswang 路过 " + DateTime.Now.ToString();
do
{
vFileStream.Seek(-vBuffer.Length * ++vReadCount, SeekOrigin.End);
vReadLength = vFileStream.Read(vBuffer, 0, vBuffer.Length);
for (int i = vReadLength - 1; i > = 0; i--)
{
j++;
if (vBuffer[i] == 10)
{
if (j == 1)
{
vLineEnd = true;
continue;
}
if (vReadCount > 1)
{
vBuffer = new byte[vFileStream.Length - j - 1];
vFileStream.Seek(j, SeekOrigin.End);
vReadLength = vFileStream.Read(vBuffer, 0, vBuffer.Length);
j = 0;
}
//textBox1.Text = Encoding.Default.GetString(vBuffer,
// vReadLength - j + 1, j - 1); //读出最后一行
vFileStream.SetLength(vFileStream.Length - (j - 1));