4

I have problem with QFile.

QFile file1("file1.dat");
QFile file2("file2.dat");

if(file2.exists())
{

}

if(!file1.open(QIODevice::ReadOnly))
{
    qDebug() << "Ошибка открытия для чтения";
}

if(!file2.open(QIODevice::WriteOnly))
{
    qDebug() << "Ошибка открытия для записи";
}

QByteArray block = file1.readAll();
file2.write(block);
file1.close();
file2.close();

ERROR:

QIODevice::read (QFile, "file1.dat"): device not open
Seanny123
  • 8,776
  • 13
  • 68
  • 124
sardorkun
  • 87
  • 2
  • 11
  • try to use ```fileN.isOpen() ``` check, for both files, to be sure they are opened. As a second step I will check their location. – wair92 Jul 22 '18 at 16:16
  • Where I need to write fileN.isOpen()? Qt already says that file1 is not opened. Also I just wrote QFile file1("file1.dat"); I want to say that I didn't create file1.dat – sardorkun Jul 22 '18 at 16:25
  • 4
    In the code shown, if `file1.open(...)` fails you still go ahead and try to read from it with `file1.readAll()`. – G.M. Jul 22 '18 at 17:04
  • 2
    What do you expect? The file can't be opened - likely it isn't there. – Kuba hasn't forgotten Monica Jul 22 '18 at 17:28

1 Answers1

3

try to open file1.dat in read-write mode:

if(!file1.open(QIODevice::ReadWrite))
{
    qDebug() << "Ошибка открытия";
}

Because if you open it just for reading, it cannot be created if it doesnt exist, or create it manually at first.

and in case that file is not opened you are not doing anything, so just for being sure check if both files were opened at first:

if(file1.isOpen() && file2.isOpen()){
    QByteArray block = file1.readAll();
    file2.write(block);
    file1.close();
    file2.close();
}
wair92
  • 446
  • 11
  • 24
  • Is it Workable? QFile File("/Users/Sardorkun/Destkop/File.txt"); – sardorkun Aug 06 '18 at 13:32
  • Also where I need to create file1.dat? – sardorkun Aug 06 '18 at 13:34
  • If It was created, where I can find file1.dat? – sardorkun Aug 06 '18 at 13:51
  • have a look on QT Documentation of QDir, methods like ```QDir::currentPath()``` or similar can be useful. And then just use ```qDebug()``` to print folder where file was created. But at first I will look to the folder, where executable is situated. (May vary depending on operating system) – wair92 Aug 06 '18 at 16:34
  • Please can you help me with my other problem? Its about sdk platforms. I already ask this question. – sardorkun Aug 07 '18 at 11:22