QFile does not open file - c++

QLabel* codeLabel = new Qlabel;
QFile file("C:\index.txt");
file.open(stderr, QIODevice::WriteOnly);
QByteArray data;
data = file.readAll();
codeLabel->setText("test"+QString(data));
file.close();
Then there is only "test" in QLabel.
Help, Please

Aside from the fact you should escape backslashes within C-style strings (c:\\index.txt), you have a problem with the following sequence:
// vvvvvvvvv
file.open(stderr, QIODevice::WriteOnly);
:
data = file.readAll();
// ^^^^
What exactly did you think was going to happen when you opened the file write-only, then tried to read it? You need to open it for reading such as with QIODevice::ReadOnly or QIODevice::ReadWrite.
On top of that, you should check the return code of all functions that fail by giving you a return code. You currently have no idea whether the file.open() worked or not.
I'm also not convinced that you should be opening stderr (which is really an ouput "device") for input. You'll almost certainly never get any actual data coming in on that file descriptor, which is probably why your input is empty.
You need to step back and ask what you're trying to acheive. For example, are you trying to capture everything your process sends to standard error? If so, it's not going to work that way.
If you're just trying to read the index.txt file, you're using the wrong overload. Remove the stderr parameter altogether:
file.open (QIODevice::ReadOnly);
If it's something else you're trying to do, add that to the question.

file.open(stderr, QIODevice::WriteOnly);
this closes the file again and reopens with the stderr stream in write only mode
you'll want to change that to
file.open(QIODevice::ReadOnly);

QFile file("C:\index.txt");
Here you try to open a file called: C:index.txt because '\i' is converted to i. You want to double you backslash:
QFile file("C:\\index.txt");

Because you read from a file you opened write-only.

Related

How to read n bytes of a file in QT C++?

Hi im new to Qt and im trying to read for example the first 4 bytes of my .txt file and show it. I've been searching and figure that QbyteArray may help me best in this situation. so I really like to know how can i read the first 4 bytes of my file with QbyteArray? (appreciate if u write any example code)
Assuming your code contains something like this:
QFile file{ "path/to/file.txt" };
You can read a number of bytes from a file with file.read(n), assuming n to be a number of bytes. you can also use file.readAll() to get the entire thing
for more advanced input/output operations, you can use the QTextStream class as such:
QFile file { "path/to/file.txt" };
QTextStream stream { &file };
(This is a stream that can read and write data to the provided device, here, a file.)
For more info, see here:
https://doc.qt.io/qt-6/qfile.html for QFile
https://doc.qt.io/qt-6/qtextstream.html for QTextStream

UTF-16LE Encoding woes with Qt text editor written in C++

So I have a QT text editor that I have started creating. I started with this http://doc.qt.io/archives/qt-5.7/gettingstartedqt.html and i have added on to it. So far I have added a proper save/save as function (the version in the link only really has a save as function), a "find" function, and an "open new window" function. Very soon, I will add a find and replace function.
I am mainly doing this for the learning experience, but I am also going to eventually add a few more functions that will specifically help me create PLC configuration files at work. These configuration files could be in many different encodings, but most of them seem to be in UTF-16LE (according to Emacs anyway.) My text editor originally had no problem reading the UTF-16LE, but wrote in plain text, I needed to change that.
Here is the snippet from the Emacs description of the encoding system of one of these UTF16-LE files.
U -- utf-16le-with-signature-dos (alias: utf-16-le-dos)
UTF-16 (little endian, with signature (BOM)).
Type: utf-16
EOL type: CRLF
This coding system encodes the following charsets:
unicode
And here is an example of the code that I am using to encode the text in my QT text editor.
First... This is similar to the link that I gave earlier. The only difference here is that "saveFile" is a global variable that I created to perform a simple "Save" function instead of a "Save As" function. This saves the text as plain text and works like a charm.
void findreplace::on_actionSave_triggered()
{
if (!saveFile.isEmpty())
{
QFile file(saveFile);
if (!file.open(QIODevice::WriteOnly))
{
// error message
}
else
{
QTextStream stream(&file);
stream << ui->textEdit->toPlainText();
stream.flush();
file.close();
}
}
}
Below is my newer version which attempts to save the code in "UTF-16LE." My text editor can read the text just fine after saving it with this, but Emacs will not read it at all. This to me says that the configuration file will probably not be readable by the programs that read it. Something changed, not sure what.
void findreplace::on_actionSave_triggered()
{
if (!saveFile.isEmpty())
{
QFile file(saveFile);
if (!file.open(QIODevice::WriteOnly))
{
// error message
}
else
{
QTextStream stream(&file);
stream << ui->textEdit->toPlainText();
stream.setCodec("UTF-16LE");
QString stream3 = stream.readAll();
//QString stream2 = stream3.setUnicode();
//QTextCodec *codec = QTextCodec::codecForName("UTF-16LE");
//QByteArray stream2 = codec->fromUnicode(stream3);
//file.write(stream3);
stream.flush();
file.close();
}
}
}
The parts that are commented out I also tried, but they ended up writing the file as Asian (Chinese or Japanese) characters. Like I said my text editor, (and Notepad in Wine) can read the file just fine, but Emacs now describes the encoding as the following after saving.
= -- no-conversion (alias: binary)
Do no conversion.
When you visit a file with this coding, the file is read into a
unibyte buffer as is, thus each byte of a file is treated as a
character.
Type: raw-text (text with random binary characters)
EOL type: LF
This indicates to me that something is not right in the file. Eventually this text editor will be used to create multiple text files at once and modify their contents via user input. It would be great if I could get this encoding right.
Thanks to the kind fellows that commented on my post here, I was able to answer my own question. This code here solved my problem.
void findreplace::on_actionSave_triggered()
{
if (!saveFile.isEmpty())
{
QFile file(saveFile);
if (!file.open(QIODevice::WriteOnly))
{
// error message
}
else
{
QTextStream stream(&file);
stream.setCodec("UTF-16LE");
stream.setGenerateByteOrderMark(true);
stream << ui->textEdit->toPlainText();
stream.flush();
file.close();
}
}
}
I set the codec of the stream, and then set the the generate BOM to "True." I guess that I have more to learn about encodings. I thought that the byte order mark had to be set to a specific value or something.I wasn't aware that I just had to set this value to "True" and that it would take care of itself. Emacs can now read the files that are generated by saving a document with this code, and the encoding documentation from Emacs is the same. I will eventually add options for the user to pick which encoding they need while saving. Glad that I was able to learn something here.

Qt - Reading file containing multiple NULL characters

I have gotten a file, which contains multiple NULL charactes /0 in a line. My goal was to load the file and replace the /0 with something else, but I experience some problems doing that.
Qt stops reading the file, after it get's to the point, where the NULL character appears.
Code:
QTextStream fileContent;
QFile file(pendingFile);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
fileContent.append(file.readAll());
}
File:
Text
Text
Text /x00/x00/x00/x00/x00/x00/x00
More Text
I am currently using Qt 5.9.1 and develop with VS2017.
Read the file with as QDataStream
QFile file("raw.dat");
file.open(QIODevice::ReadOnly);
QDataStream fileStream(&file);
qint64 fileSize = file.size();
QByteArray data(fileSize, '\0');
fileStream.readRawData(data.data(), fileSize)
In the ByteArray you can replace all \0 elements.
Update (comments, look at underscore_d's answer):
data.replace('\0','_');
QString dataString(data);
The problem is not that QFile stops reading at NUL (i.e. '\0', not the NULL macro), but rather that QTextStream considers a NUL to mean end-of-string and thus stops append()ing after the first NUL it encounters.
Here is a previous thread on another site discussing something very similar, with a suggested alternative, which boils down to this:
You need to replace the NULs before feeding them into the QTextStream, as it will not pass them through. The suggestion there is to use a QDataStream. Maybe you don't need a TextStream or any Stream at all, and could just read the files into memory as binary and replace the NULs with your choice of substitute before writing out again.

evaluateJavaScript used for an entire file

I need an editor of mine to evaluate the JS code in whatever JS file I have open. However, it never does. Although the app output says
QIODevice::read: device not open
Here's my code (mFilename is the variable that holds the open file's filename)
QFile sFile(mFilename);
QTextStream in(&sFile);
text = in.readAll();
sFile.close();
ui->webView->page()->mainFrame()->evaluateJavaScript(text);
You forgot to open the file. To open it you have to use QFile::open method.
If you want to read it just call the file.open like that:
sFile.open(QIODevice::ReadOnly);
Indeed you didn't open the file by calling the QFile constructor.
So, your code would now be:
QFile sFile(mFilename);
QTextStream in(&sFile);
sFile.open(QIODevice::ReadOnly);
text = in.readAll();
sFile.close();
ui->webView->page()->mainFrame()->evaluateJavaScript(text);

Delete-file option before opening a file using QFile::Append

Most of the time I want to iteratively add a line to a file, but before I open the file to append to, I'd want to be sure it is an empty file to start with (delete if exists).
It occurs so often that I am guessing there might be something I overlook.
So, what is the most convenient way to remove a file first before appending?
QFile outfile(filename);
if (outfile.open(QFile::Append | QFile::Text))
// An option like `QFile::DELETE_FIRST` or something would be great.
{
...
}
Just don't use QFile::Append - it will open file in append mode, so that all dta is written to the end of the file. You can see all OpenModeFlag's here. Use QIODevice::Truncate instead.
QIODevice::Truncate If possible, the device is truncated before it is opened. All earlier contents of the device are lost.