编辑文件内容

时间:2013-07-04 17:02:21

标签: file-io textbox c++-cli editing overwrite

在Form1中,我有2个TextBox(姓氏和名字)。当我按下“注册”按钮时,我通过TextWriter将它们写入文件。每行包含姓氏和名称,因此每行有2个字段。

在Form2中,我想通过询问参数来编辑它们。例如,在Form2中,我有一个TextBox。如果我在TextBox中输入的姓氏等于我的文件中的一个,我想在Form1中的正确TextBox中显示姓氏和姓名,并且在编辑姓氏或姓名之后我想通过按下“注册”来覆盖正确位置的前一行“按钮。

感谢用户Medinoc,我写了这样的文件:

ref class MyClass
{
public:
    String^ cognome;
    String^ nome;
};

//...

List<MyClass^>^ primo = gcnew List<MyClass^>();

//...

MyClass^ myObj = gcnew MyClass();
myObj->cognome = textBox1->Text;
myObj->nome = textBox2->Text;
primo->Add(myObj);

//...

TextWriter ^tw = gcnew StreamWriter(L"primoAnno.txt", true);
for each(MyClass^ obj in primo)
{
    //You can use any character or string as separator,
    //as long as it's not supposed to appear in the strings.
    //Here, I used pipes.
    tw->Write(obj->cognome);
    tw->Write(L"|");
    tw->Write(obj->nome);
}
tw->Close();

READ

MyClass^ ParseMyClass(String^ line)
{
    array<String^>^ splitString = line->Split(L'|');
    MyClass^ myObj = gcnew MyClass();
    myObj->cognome = splitString[0];
    myObj->nome = splitString[1];
    return myObj;
}

希望我足够清楚。我不是英格兰人。 在此先感谢!!

1 个答案:

答案 0 :(得分:0)

它仍然是经典的文本文件编辑行为:

您需要的是搜索文件中特定行的功能;和另一个修改特定行的功能。那个类似于the deleting code

查找:

MyClass^ FindMyClass(String^ surnameToFind)
{
    MyClass^ found = nullptr;
    TextReader^ tr = gcnew StreamReader(L"primoAnno.txt");
    String^ line;
    while(found == nullptr && (line=tr->ReadLine()) != nullptr)
    {
        MyClass^ obj = ParseMyClass(line);
        if(obj->cognome == surnameToFind)
            found = surnameToFind;
    }
    tr->Close();
}

更新

MyClass^ objToUpdate = gcnew MyClass;
objToUpdate->cognome = textBox1->Text;
objToUpdate->nome = textBox2->Text;

TextWriter^ tw = gcnew StreamWriter(L"primoAnno2.txt", true);
TextReader^ tr = gcnew StreamReader(L"primoAnno.txt");
String^ line;
bool updated = false;
while((line=tr->ReadLine()) != nullptr)
{
    MyClass^ obj = ParseMyClass(line);
    if(obj->cognome == objToUpdate->cognome)
    {
        line = objToUpdate->cognome + L"|" + objToUpdate->nome;
        updated = true;
    }
    tw->WriteLine(line);
}
//If the surname was not in the file at all, add it.
if(!updated)
{
    line = objToUpdate->cognome + L"|" + objToUpdate->nome;
    tw->WriteLine(line);
}
tr->Close();
tw->Close();
File::Delete(L"primoAnno.txt");
File::Move(L"primoAnno2.txt", L"primoAnno.txt");