2013-10-20 33 views
1

我嘗試使用下面的代碼讀取一個文本文件中的垃圾字符:麻煩,在Visual C++文件讀取

void function readfile(char *inputfile) { 
istream is; 
int filesize = 0; 

is.open(inputfile); 
if (!is.is_open()) { 
return; 
} 
is.seekg(0, ios::end); 
filesize = (int)is.tellg(); 
is.seekg(0, ios::beg); 

char *buf = new char[filesize]; 
is.read(buf, filesize); 
is.close(); 

cout << buf << endl; 

delete[] buf; 
return; 
} 

而在G ++(MAC/MacPorts的),它工作正常(讓所有的內容爲動態分配的char *數組),在Visual Studio C++ 2010中,我得到這種類型的常量錯誤:Debug assertion failed: (unsigned)(c+1) <= 256, file isctype.c

問題是,它打開文件,但無法找到終止分隔符,所以當它到達eof它開始讀取其他地方(垃圾字符)。使用cout << buf;我可以看到文件在mac中被正確讀取,但在visual C++中它輸入了更多的垃圾字符。這裏有什麼問題?

回答

1

令C++標準庫做的工作適合你:

void readfile(const char *inputfile) { 
    std::ifstream is(inputfile); 
    std::string buf(std::istreambuf_iterator<char>(is), {}); 
    std::cout << buf << std::endl; 
} 

看到,它現在也

  • 異常安全
  • 處理內嵌的NULL字符正確

注,當然你可以使用vector而不是string如果你願意R(只是改變一個詞)

完整的示例:see it live on Coliru

#include <fstream> 
#include <iostream> 
#include <iterator> 

void readfile(const char *inputfile) { 
    std::ifstream is(inputfile); 
    std::string buf(std::istreambuf_iterator<char>(is), {}); 
    std::cout << buf << std::endl; 
} 

int main() 
{ 
    readfile("main.cpp"); 
} 

更新對於C++ 11個的挑戰編譯器(和展示如何使用向量):

而且Live on Coliru

#include <fstream> 
#include <iostream> 
#include <iterator> 
#include <vector> 

void readfile(const char *inputfile) { 
    std::ifstream is(inputfile); 
    std::istreambuf_iterator<char> f(is), l; 
    std::vector<char> buf(f, l); 

    std::cout.write(buf.data(), buf.size()); 
} 

int main() 
{ 
    readfile("main.cpp"); 
} 
+0

非常有見識的sehe。我實際上正在努力實現它,因爲它是我的課程指導的(這是程序的一部分)。問題是我們不允許使用字符串類,並且我一直在更多地在我的Mac上進行練習,而不是在視覺工作室所在的PC上(並且應該是主要的IDE)。我最感興趣的是由mscompiler生成的錯誤,並從g ++傳遞。 – Panagiotis

+1

@Panagiotis那麼,使用該矢量然後:/要做到這一點(使用'vector','std :: cout.write' _and_滿足MSVC)看到更新的答案(也[在線直播](http://coliru.stacked -crooked.com/a/e257bf50affa21da)) – sehe

3

使您的緩衝區變大一點,並自己添加終止節點。

+0

或者,使用'cout.write(buf,filesize)',或者直接使用標準庫(參見我的回答) – sehe

+0

Scott,我試過之後我在這裏發佈了這個問題,我也遇到了同樣的錯誤,即使在寫作流(這個程序的另一部分)中也是如此。這可能是一個unicode的東西嗎?即使該文件從記事本保存在ANSI? – Panagiotis