我是C ++和CLI / C ++的新手,我遇到了问题。我想用我选择的不同文本替换文本文件中的行。例如,我有一个包含12行的文本文件,我想要替换第6行,即“第6行”,文本“第6行编辑”。 现在,我刚刚开始学习如何处理文本文件,我已经想出如何插入行,所以我目前所拥有的所有代码都是:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
char txtfile[]="C:\\Users\\acer\\Desktop\\aaa.txt";
StreamWriter ^writer = gcnew StreamWriter(gcnew String(txtfile),true);
writer->WriteLine("Line 1");
writer->WriteLine("Line 2");
writer->Close();
delete writer;
}
根据我的研究,我发现我有两种方法可以做到这一点。我可以使用临时文件,或者我可以将所有行加载到数组中,如果文件不是太大,则将其存储在内存中。文件是1KByte所以我想使用第二种方法将其存储在内存中。现在,我的问题是,由于我是这种语言的新手,我不知道如何实际做到这一点。我一直在寻找能否找到如何做的指示 这在CLI C ++中,但我找不到任何东西。我一直在这里看这个主题 - > Delete specific line from a text file? 但它是在C#中,我不知道如何将代码转换为CLI C ++。
编辑:我看过其他主题的C#代码,其中显示了如何删除一行,我想尝试一下
var file = new List<string>(System.IO.File.ReadAllLines("C:\\path"));
file.RemoveAt(12);
File.WriteAllLines("C:\\path", file.ToArray());
我试图在CLI / C ++中转换为这样的东西:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
char txtfile[]="C:\\Users\\acer\\Desktop\\aaa.txt";
array<String^>^ fileArray = System::IO::File->ReadAllLines(txtfile);
fileArray->Remove(6);
File->WriteAllLines(txtfile, fileArray->ToArray());
}
但我没有成功,因为我不知道CLI / C ++的正确语法,因为我是新手。如何在CLI C ++中使用该C#代码?我非常感谢这些说明,但我需要CLI / C ++中的代码示例。
答案 0 :(得分:0)
您似乎混淆了静态和非静态方法:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
System::String^ txtfile = L"C:\\Users\\acer\\Desktop\\aaa.txt";
array<System::String^>^ lineArray = System::IO::File::ReadAllLines(txtfile);
System::Collections::Generic::List<System::String^>^ lineList;
lineList = gcnew System::Collections::Generic::List<System::String^>(lineArray);
lineList->RemoveAt(6);
System::IO::File::WriteAllLines(txtfile, fileList->ToArray());
}