[英]C++ file handling IO errors
我的代碼如下:
假設寫入 100 個隨機數並將它們保存到一個文件中,然后將它們保存在我的三個數組中: masiv1
、 masiv2
和masiv3
。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ofstream outFile;
ifstream inFile;
string homeDir = getenv("HOME");
homeDir = homeDir + "/testovFile.txt";
outFile.open(homeDir);
int masiv1[100],masiv2[100],masiv3[100];
if(!outFile.fail()){
for (int i = 0; i < 100; ++i)
{
outFile << (rand() % 100) << "\n";
}
outFile.close();
} else {cout << "File open failed!" << endl;}
inFile.open(homeDir);
if(!inFile.fail()){
for (int i = 0; i < 100; ++i)
{
inFile >> masiv1[i];
inFile >> masiv2[i];
inFile >> masiv3[i];
}
for (int i = 0; i < 100; ++i) {
cout << masiv1[i] << endl;
}
inFile.close();
} else {cout << "File open failed!" << endl;}
}
輸出:
7
58
44
9
92
3
40
69
60
78
97
67
79
21
93
45
94
53
68
96
22
24
77
33
35
14
25
94
17
4
88
82
16
44
0
0
0
0
0
0
44026832
1
0
0
1833038584
1
33554432
64
47572408
1
47572428
1
1833038688
1
16
0
1
0
44026832
1
0
0
0
0
0
0
0
0
44026832
1
1833040336
1
16777234
28
48038656
1
1833039808
1
47576748
1501495297
1833041766
1
1920169263
1651076143
-1799393720
1
-1799393872
1
1833039039
1
1833039120
1
1833038960
1
47765896
1013383169
720977920
0
603620773
0
這里有幾個問題:
using namespace std;
打開完整的std
命名空間;std::array
或std::vector
std::filesystem
和std::path
因此,請始終檢查 IO 操作(例如使用>>
)是否有效。
在你的循環中
for (int i = 0; i < 100; ++i)
{
inFile >> masiv1[i];
inFile >> masiv2[i];
inFile >> masiv3[i];
}
您正在調用提取操作員 300 次。 對於文件中的 100 個元素。 而且您不檢查 IO 操作的結果。
您在輸出中也可以看到這一點。
例子:
Value 1 is assigned to masiv1[0]
Value 2 is assigned to masiv2[0]
Value 3 is assigned to masiv3[0]
Value 4 is assigned to masiv1[1]
Value 5 is assigned to masiv2[1]
Value 6 is assigned to masiv3[1]
Value 7 is assigned to masiv1[3]
Value 8 is assigned to masiv2[3]
Value 9 is assigned to masiv3[3]
. . .
. . .
Value 99 is assigned to massive3[32]
Value 100 is assigned to massive1[33]
Value 101 is not existing. IO operation fails. All further `>>` will be skipped
正如你所看到的。 最后寫入的值在 mass1[33] 中。 所以,第 34 個值。 因為您沒有初始化這些值,所以其余的都是不確定的。
您在輸出中也可以看到這一點。
因此,請始終檢查 IO 操作的任何結果,然后采取相應措施。
檢查可以通過例如if (infile)
來完成。 這是可行的,因為std::stream
的bool
運算符已被覆蓋。 請看這里。
同樣適用於if (inFile >> masiv1[i])
,因為插入器將返回對調用它的std::ifstream
的引用。 然后bool
運算符將再次啟動。
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.