QT - How set filename encoding to cyrillic - c++

when creating a file named "абцде"
the filename is written with hieroglyphics
const QByteArray data = "someData"; // some Data
QString fileName = "абцде.txt"; // fileName
QFile localFile(fileName.toUtf8());
localFile.open(QIODevice::WriteOnly);
localFile.write(data);
localFile.close();

These lines of code form qt man on internationalization
can help. ( QString use Unicode originally ).
QTextCodec *codec = QTextCodec::codecForName( "Windows-1251" );
QByteArray encodedString = codec->fromUnicode( "абцде.txt" );
You might need to play around with encodings ( "Windows-1251" ), kind of brute force method.

If your sources are UTF8 encoded, then you should use this (Qt Documentation)
QString fileName = QString::fromUtf8( "абцде.txt" ); // fileName
If your sources has other encoding then you can select other functions like QString::fromLocal8Bit.

Related

How do I get the value of text inside of the file using Qt?

The data of my file.txt is as below:
Student_ID=0001
Student_Name=joseph
Student_GradeLevel=2
How do I get the value, let say I want to get the Student_ID using Qt.
Thanks.
Take a look at this function, it can be used to find any value you want in your input file, where all lines are in the format you've posted above (key=value). If the key is not found, it returns an empty QString() object.
QString findValueInFile(QString key, QString filename) {
QFile file(filename);
if(file.open(QIODevice::ReadOnly)) {
QTextStream txtStr(&file);
QStringList fileContent = txtStr.readAll().split('\n');
for(auto &&line : fileContent) {
if(line.contains(key)) return line.split(QChar('='))[1];
}
file.close();
}
return QString(); // not found
}
Now you call it somewhere, e.g.:
qDebug() << findValueInFile("Student_ID", "file.txt");
qDebug() << findValueInFile("Student_Name", "file.txt");
This function can be easily modified if you replace your = sign with other delimiter e.g. => or sth else. However for key=value format there is a special QSettings class (mentioned by sebastian) that can allow you to read those values even easier:
QSettings file("file.txt", QSettings::IniFormat);
qDebug() << file.value("Student_Name").toString(); // et voila!
You can probably also use QSettings, as they are able to read ini files.
There are some caveats though regarding backslashes which might be important to you (though they aren't for the example you posted): http://doc.qt.io/qt-4.8/qsettings.html#Format-enum
QSettings iniFile("myfile.txt", QSettings::IniFormat);
// now get the values by their key
auto studentId = iniFile.value("Student_ID").toString().toInt();
I'm more of a PyQt user, so: apologies if I got some C++ specifics wrong...

Qt - How to copy file with QFile::copy using QFileDialog?

QString filename = QFileDialog::getOpenFileName(this,tr("Pdf files"), "C:/", "books(*.pdf)");
I want to get the selected file from QFileDialog and copy it to my desktop. Can I use something like this?
QFile::copy(filename,"desktop");
You need to get the path to the desktop using QStandardPaths, and then use that path in your call to QFile::copy.
Assuming you want to preserve the file name while copying, your code will look something like this:
QString filePath = QFileDialog::getOpenFileName(this ,
QObject::tr("Pdf files"),
"C:/", "books(*.pdf)");
QFileInfo fi(filePath);
QString fileName= fi.fileName();
QString desktopPath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
QString destinationPath= desktopPath+QDir::separator()+fileName;
if(QFile::copy(filePath, destinationPath))
qDebug() << "success";
else
qDebug() << "failed";

Removing extension of a file name in Qt

I'm using Qt to get a file name from the user:
QString fileName = QFileDialog::getOpenFileName(this,tr("Select an image file"),"d:\\",tr("Image files(*.tiff *.tif )"));
It works, but I need the file name without its extension, is it possible in Qt??
whenn I try :
QString f = QFileInfo(fileName).fileName();
f is like "filename.tif", but I want it to be "filename".
QFileInfo has two functions for this:
QString QFileInfo::completeBaseName () const
Returns file name with shortest extension removed (file.tar.gz -> file.tar)
QString QFileInfo::baseName () const
Returns file name with longest extension removed (file.tar.gz -> file)
To cope with filenames containing multiple dots, look for the last one and take the substring until that one.
int lastPoint = fileName.lastIndexOf(".");
QString fileNameNoExt = fileName.left(lastPoint);
Of course this can (and should) be written as a helper function for reuse:
inline QString withoutExtension(const QString & fileName) {
return fileName.left(fileName.lastIndexOf("."));
}
You can split fileName with "." as separator like this:
QString croped_fileName=fileName.split(".",QString::SkipEmptyParts).at(0);
or use section function of QString to take the first part before "." like this:
QString croped_fileName=fileName.section(".",0,0);
You can use QString::split and use the . as the place where to split it.
QStringList list1 = str.split(".");
That will return a QStringList with {"filename", "extenstion"}. Now you can get your filename without the extension.
To get absolute path without extension for QFileInfo fileInfo("/a/path/to/foo.tar.gz") you can use:
QDir(file_info.absolutePath()).filePath(file_info.baseName());
to get "/a/path/to/foo" or
QDir(file_info.absolutePath()).filePath(file_info.completeBaseName());
to get "/a/path/to/foo.tar"

Convert a multiline QString into a one line QString

I have something like this:
void ReadFileAndConvert ()
{
QFile File (Directory + "/here/we/go");
if(File.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream Stream (&File);
QString Text;
do
{
Text = Stream.readLine();
Text = Text.simplified();
// Here I want to convert the multiline QString Text into a oneline QString
// ...
}
The QString Text consists of a multiline Text that I need to convert into a online Text/QString. How can I achieve this? greetings
Put your text into a QStringList, and use QStringList::join(), e.g.
QStringList doc;
[...]
Text = Stream.readLine();
Text = Text.simplified();
doc << Text;
[...]
QString final = doc.join(" ");
You could use the readAll function of QTextStream in order to get a string containing all your text and then use the replace function of QString in order to remove new lines:
QString oneLineText = Stream.readAll().replace("\n"," ").simplified();
If you have a large file it is better to use the readLine function.

Qt C++ writing data in a file , unexpected output

I have a task to save a file to computer. So this is my problem, when i write to file , it writes hex values.. I have no clue, what's wrong with my code. Here it is:
void MainWindow::on_actionSave_triggered()
{
QString filename = QFileDialog::getSaveFileName(
this,
tr("Save Document"),
QDir::currentPath(),
tr("Documents (*.txt)") );
QFile f( filename );
f.open( QIODevice::WriteOnly | QIODevice::Text );
QTextStream out(&f);
out << ui->textEdit->document();
}
QTextEdit's document method return QTextDocument, I think you want to use toPlainText method instead.
QTextEdit::document() will return a QTextDocument* which will be an Hex value (address). That's what you are adding in the file.
To get the contents from the QTextEdit use QString QTextEdit::toPlainText ()
HTH..