2011-03-19 87 views
9

我正在使用Visual C++ 2008. 我想創建一個文本文件並在其上寫入。創建一個文本文件並在其上寫入

char filename[]="C:/k.txt"; 
FileStream *fs = new FileStream(filename, FileMode::Create, FileAccess::Write); 
fstream *fs =new fstream(filename,ios::out|ios::binary); 
fs->write("ghgh", 4); 
fs->close(); 

這裏是在FILESTREAM

+0

請修改您的帖子並添加您的確切錯誤消息。此外,完整的代碼(正確格式化,與標題)可能會有所幫助。 – Mat 2011-03-19 14:15:51

+0

@user:'FileStream'從哪裏來?你爲什麼創建兩個流?爲什麼要動態創建流?你是轉換爲C++的Java程序員嗎? – 2011-03-19 14:18:14

+1

FileStream?這是一個.NET類嗎?你想要做C++嗎?還是C++/CLI? – 2011-03-19 14:18:44

回答

12

的錯誤,因爲你有fs兩種不同的方式宣佈兩次你得到一個錯誤;但我不會保留任何代碼,因爲它是C++和C++/CLI的奇怪組合。

在你的問題不清楚你是否想要做標準的C++或C++/CLI;假設你想要的「正常的」 C++,你應該做的:

#include <fstream> 
#include <iostream> 

// ... 

int main() 
{ 
    // notice that IIRC on modern Windows machines if you aren't admin 
    // you can't write in the root directory of the system drive; 
    // you should instead write e.g. in the current directory 
    std::ofstream fs("c:\\k.txt"); 

    if(!fs) 
    { 
     std::cerr<<"Cannot open the output file."<<std::endl; 
     return 1; 
    } 
    fs<<"ghgh"; 
    fs.close(); 
    return 0; 
} 

請注意,我刪除了所有new東西,因爲很多時候你不需要它在C++ - 你可以分配在堆棧上的流對象和忘記你的代碼中存在的內存泄漏,因爲正常的(非GC管理的)指針不經受垃圾收集。

+3

可以*而且應該* [只是在堆棧上分配] – 2011-03-19 14:49:56

3

以下是本機和託管C++的例子:

假設你很高興與本地解決了以下工作得很好:

fstream *fs =new fstream(filename,ios::out|ios::binary); 
fs->write("ghgh", 4); 
fs->close(); 
delete fs;  // Need delete fs to avoid memory leak 

不過,我不會用動態內存爲fstream的對象(即新的陳述和要點)。這是新版本:

fstream fs(filename,ios::out|ios::binary); 
fs.write("ghgh", 4); 
fs.close(); 

編輯,問題被編輯要求的本地解決方案(最初它不清楚),但我會離開這個答案,因爲它可能是使用的人

如果您正在尋找C++ CLI選項(用於託管代碼),我推薦使用StreamWriter而不是FileStream。 StreamWriter將允許您使用託管字符串。請注意,刪除將調用IDisposable接口的Dispose方法和收集最終將釋放內存的垃圾:

StreamWriter ^fs = gcnew StreamWriter(gcnew String(filename)); 
fs->Write((gcnew String("ghgh"))); 
fs->Close(); 
delete fs; 
-3

您創建一個文本。詢問用戶是否想要發送它。如果他說是的,這意味着這個特定的消息應該被標記爲發件箱消息,否則它應該是收件箱消息。

+1

問題很明顯是關於'.txt'文件,而不是SMS消息。此答案中沒有任何內容與文本文件或Visual C++ 2008相關。 – 2014-04-02 19:57:14

+0

@Amad Munir發佈該答案時你在想什麼 – 2016-06-04 13:28:14

相關問題