2011-03-31 20 views
0

爲什麼一切都被讀爲0?C++文件I/O錯誤?

int width = 5; 
    int height = 5; 
    int someTile = 1; 
    char buff[128]; 


    ifstream file("test.txt", ios::in|ios::binary); 

    if(file.is_open()) 
    { 
     cout << "open"; 
    } 

    file.read(buff, sizeof(int)); 
    width = atoi(buff); 

    file.read(buff, sizeof(int)); 
    height = atoi(buff); 

    for (int x = 0; x < width; x++) { 
     for (int y = 0; y < height; y++) { 
      file.read(buff, sizeof(int)); 
      someTile = atoi(buff); 
      cout << someTile; 
     } 
    } 

我的文件格式的代碼是在C#和這樣寫的:

FileStream stream = new FileStream("test.txt", FileMode.Create); 
      BinaryWriter writer = new BinaryWriter(stream); 
      // write a line of text to the file 

      writer.Write(15); 
      writer.Write(5); 

      for (int i = 0; i < 15; i++) 
      { 
       for (int j = 0; j < 5; j++) 
       { 
        writer.Write(1); 
       } 
      } 

      // close the stream 
      writer.Close(); 
+0

不是挑剔的,但你不需要ios :: in與ifstream,它已經被定義爲輸入。如果您的文件打開失敗會發生什麼,您嘗試讀取數據。 – jonsca 2011-03-31 08:13:35

+0

你似乎以二進制模式打開文件,但後來像處理文本一樣處理數據。爲什麼不首先在文本模式下打開文件? – 2011-03-31 08:13:53

+0

我可能有一個更簡單的解決方案,但因爲我不確定,所以我發佈了[作爲問題](http://stackoverflow.com/questions/5497284/)。 – 2011-03-31 08:47:43

回答

1

不知道test.txt的內容是很難說清楚,但它看起來像你反覆讀4字節(大多數平臺上的int大小)轉換爲字符緩衝區/字符串,然後嘗試將其轉換爲數字。除非你的文件完全由四個空字符結尾的字節塊構成,否則我不會期望這個工作。

更新:好吧,看看你的文件格式,你不寫字符串,你寫的是整數。因此,我希望您能夠直接讀入您的號碼,不需要atoi

例如:

​​

value現在應該包含從文件的數量。要轉換您的整個例子中,你正在尋找的東西是這樣的:

int width = 5; 
int height = 5; 
int someTile = 1; 

ifstream file("test.txt", ios::in|ios::binary); 

if(file.is_open()) 
{ 
    cout << "open"; 

    file.read(reinterpret_cast<char*>(&width), sizeof(int)); 
    file.read(reinterpret_cast<char*>(&height), sizeof(int)); 

    for (int x = 0; x < width; x++) { 
     for (int y = 0; y < height; y++) { 
      file.read(reinterpret_cast<char*>(&someTime), sizeof(int)); 
      cout << someTile; 
     } 
    } 
} 
+0

好吧,看看第一篇文章。添加信息。 – CyanPrime 2011-03-31 08:17:49

+0

| 45 |錯誤:沒有匹配函數調用'std :: basic_ifstream > :: read(int *,unsigned int)' – CyanPrime 2011-03-31 08:23:52

+0

當我嘗試時仍然收到相同的錯誤。沒有匹配的函數調用'std :: basic_ifstream > :: read(int *,unsigned int)' – CyanPrime 2011-03-31 08:27:58

0

atoi轉換NUL結尾的字符串爲整數 - 您是從文件(這是二進制模式)在讀取四個字節 - 這可能不正確..

例如,一個有效的字符串(atoi工作可能是,「1234」 - 注意:NUL終止),但是這個字節表示是0x31 0x32 0x33 0x34(注意NUL終止給你只能讀取4個字節,因此,atoi可以做任何事情)。這個文件的格式是什麼?如果它真的是字節表示,數字1234將看起來像(取決於字節數),0x00 0x00 0x04 0xD2,正確讀取這個int的方法是逐字節地移位。

那麼,大問題 - 格式是什麼?

+0

添加格式代碼到第一篇文章 – CyanPrime 2011-03-31 08:19:14