Portál AbcLinuxu, 5. prosince 2025 19:02
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// otevreni pro cteni i zapis
fstream *dbFile = new fstream("file.txt", ios::in | ios::out | ios::binary);
if (!dbFile->is_open()) { // soubor nelze otevrit
cout << "Creating file" << endl;
dbFile->open("file.txt", ios::out | ios::binary); // vytvoreni souboru
if (!dbFile->is_open()) {
cout << "Cannot create file" << endl;
return 0;
}
dbFile->close();
// otevreni pro cteni i zapis
dbFile->open("file.txt", ios::in | ios::out | ios::binary);
if (!dbFile->is_open()) {
cout << "Cannot open file after create" << endl;
return 0;
}
if (!dbFile->write("AABB", 4))
cout << "Cannot write to file" << endl;
dbFile->close();
}
else
cout << "Opening file" << endl;
delete dbFile;
return 0;
}
#include <fstream>
using namespace std;
int main()
{
// jako fopen(..., "r+") => O_RDRW
fstream *dbFile = new fstream("file.txt", ios::in | ios::out);
if (!*dbFile) {
dbFile->clear();
// jako fopen(..., "w+") => O_RDRW | O_TRUNC | O_CREAT
dbFile->open("file.txt", ios::in | ios::out | ios::trunc);
}
if (!*dbFile) {
perror("file.txt");
return 1;
}
if (!dbFile->write("AAXB", 4)) {
perror("writing to file.txt");
return 1;
}
dbFile->close();
delete dbFile;
return 0;
}
delete dbFile; i při chybě (nebo mít dbFile na zásobníku...). Ale podstatné je to volání dbFile->clear() a to, že dbFile->open() stačí volat dvakrát.
Dík.
twofish uz te zrejme uspokojil:). jen bych dodal pro inspiraci jine reseni:
#include <iostream>
#include <fstream>
using namespace std;
namespace {
const string JMENO = "file.txt";
}
int main() {
fstream test;
test.exceptions ( ifstream::eofbit | ifstream::failbit | ifstream::badbit );
try {
test.open ( JMENO.c_str(), ios::in | ios::out | ios::binary | ios::trunc);
}
catch (ifstream::failure &e) {
cerr << e.what() << ":"<< endl;
perror ("Vyjimka otevreni/cteni ze souboru.");
exit(1);
}
return 0;
}
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.