Open and read from a file c++
Cours : Open and read from a file c++. Recherche parmi 300 000+ dissertationsPar Hamed Arous • 16 Janvier 2023 • Cours • 507 Mots (3 Pages) • 250 Vues
We can then perform the same operations on these streams as on cin and cout: operators >> and <<, getlinefunction, ...
There are four methods to check the status of a stream at any time:
- eof(): in read mode, when the end of a file is encountered ;
- fail(): logical error while reading or writing ;
- bad(): system error which reading or writing ;
- good(): all is ok ;
and two methods to manage the status of a file :
- bool is_open() checks that the stream is open;
- void close() closes the stream (obligatory at the end of each use).
Examples
Writing a sequence of integers in a file:
int main()
{
string fileName;
ofstream output;
vector<int> v = {1,2,40,5,7,8,10};
try {
cout << "Name of file to create?";
cin >> fileName;
output.open(fileName);
if(!(output.is_open())) throw(fileName);
output << v.size() << endl;
for(int i=0; i<v.size(); i++)
output << v[i] << ' ' ; // do not forget to include a separator
output << endl;
output.close();
} catch (string s) {
cerr<< "Problem encountered while opening file: " << fileName;
}
return 0;
}
Reading a sequence of integers from a file:
int main()
{
string fileName;
ifstream input;
vector<int> v(0);
try {
cout << "Name of file to read?";
cin >> fileName;
input.open(fileName);
if(!(input.is_open())) throw(fileName);
int nbInt;
if (!input.eof())
input >> nbInt;
for (int i = 0; i < nbInt && !input.eof(); i++) {
int val;
input >> val;
v.push_back(val);
}
input.close();
cout << "We have read:";
for (int i = 0; i < v.size(); i++) {
cout << " " << v[i];
}
cout << endl;
} catch (string s) {
cerr<< "Problem encountered while opening file : " << fileName;
}
return 0;
}
...