2015-05-10 143 views
1

试图读取和写入.txt文件中的数据。阅读工作正常,但每次我尝试写入时,都会覆盖之前写入的内容。只有最后写的东西仍然存在。在txt文件中写入

void    trace(Board& tab) 
{ 
    ofstream  file("trace.txt", ios::in | ios::trunc); 
    Position  pos(0,0); 
    Position&  p = pos; 

    if(file) 
    { 
     for (int i = 0; i < tab.getNbline(); i++) 
     { 
      for(int j = 0; j < tab.getNbcolumn(); j++) 
      { 

       p.setposition(i,j); 

       if(i == tab.getEmptyline() && j == tab.getEmptycolumn()) 
       { 

        file << setw(tab.getNbcolumn()) << tab.getValue(p); 

        if (j == tab.getNbcolumn()-1) 
        { 
         file << endl; 
        } 
       } 
       else 
       { 

        file << setw(tab.getNbcolumn()) << tab.getValue(p); 
        if (j == tab.getNbcolumn()-1) 
        { 
         file << endl; 
        } 
       } 
      } 
     } 
     file.close(); 
    } 
    else cerr << "Cannot open file" << endl; 
} 

void trace_message(string str) 
{ 
    ofstream  file("trace.txt", ios::in | ios::trunc); 
    if(file) 
    { 
      file << str << endl; 
      file.close(); 
    } 
    else cerr << "Cannot open file" << endl; 

} 

任何想法?是否因为“ios :: trunc”? (我不知道这是什么意思)

+0

这里回答。 http://www.cplusplus.com/doc/tutorial/files/ – 911

回答

3

Repalce的ios :: TRUNC内部监督办公室::应用程序(附加在文件末尾)

+0

它的工作:3我有一个想法seek()和ios :: end,但你的解决方案工作得很好,谢谢:) – Csi

+0

我可以问这个话题的另一个问题?这是关于一个奇怪的东西写在我的txt文件中,当我尝试写下这样的东西:“str =”Nombre d'iterations“+ nbiter;”举个例子。 – Csi

+0

@Csi你的意思是你的txt文件对你来说不可读(不是UTF-8)? – Dien

1

如果你想在文件中,你应该使用ifstream的编写。但是,由于您正在阅读文件,如果您只使用fstream,它会更好。

http://www.cplusplus.com/reference/fstream/ofstream/ofstream/

在链接页面,您可以阅读有关TRUNC,你不明白。

对不起,如果我的英文不好。还在学习它。

+0

我认为你的意思是“ofstream”,而不是“ifstream”。 – Beta

+0

据我所知,ifstream用于阅读,ofstream用于写作,fstream用于两者。 – Csi