I want to do a telnet client. There is no problem to connect modem and read QTcpSocket.
void iDirectClient::when_socket_ready_read() {
QByteArray ba = m_socket->readAll();
qDebug() << "\r\nRead:\r\n" << ba;
QString filename = "my_file.txt";
QFile file(filename);
if (file.open(QIODevice::ReadWrite)) {
QTextStream stream(&file);
stream << ba << endl
}
file.close();
}
and I use FileIO for read a text file in QML.Here is my code:
QFile file(m_source);
QString fileContent;
if ( file.open(QIODevice::ReadOnly) ) {
QString line;
QTextStream t( &file );
do {
line = t.readLine();
fileContent += line;
}
while (!line.isNull());
qDebug() << "SOURCE" << line;
file.close();
file.remove();
}
When I create my_file.txt, there is no problem. It seems like
"677 = T12V_KU_SAT
623 = SBC2_KU_SEA
615 = IS19_KU_SWP" (these are beam list.)
but I read this text file in QML, with this code:
FileIO {
id: myFile
source: "my_file.txt"
onError: console.log(msg)
Component.onCompleted: {
}
}
Component.onCompleted: {
console.log(myFile.read())
textarea1.text = myFile.read();
}
"677 = T12V_KU_SAT623 = SBC2_KU_SEA615 = IS19_KU_SWP" output is like this.
I want to display every beam in listview because I need to beams names are clickable.There is a problem with line feed.
I hope I explained clear my problem.Thank you!
The string returned by QTextStream::readLine() does not contain end-of-line characters according to the documentation.
Related
Instead of overwriting the new text, I want to preserve the existing content and add it to the new line.
I need make a simple log for login. But When I try save to txt file Is overwriting on file. But when I try it, It just overwriting on file. How can I add to new line when new log is coming?
Here is my login function
void loginpage::on_lgnBtn_clicked() {
login = ui -> lgnUname -> text();
password = ui -> lgnPass -> text();
QString passwordhash = passwordHash(password.toUtf8());
qDebug() << passwordhash;
if (login == "admin" && passwordhash == getTxtPassword()) {
loginLog();
hide();
mw = new MainWindow(this);
mw -> show();
} else {
QMessageBox::warning(nullptr, "Hata", "Kullanıcı adınız veya şifreniz hatalı!");
loginLog();
}
}
Here is my function for write to file.
void loginpage::loginLog() {
QString TEXT_DIR = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/test/log.txt";
QFile file(TEXT_DIR);
if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream stream( & file);
QString UnameLog = login;
QString PassLog = password;
stream << "Giriş yapıldı";
stream << "\n";
stream << UnameLog;
stream << "\n";
qDebug()<< UnameLog;
stream << PassLog;
file.close();
} else {
qDebug() << "hata log yazılamadı";
}
}
I think there is something missing or wrong, but I couldn't figure it out. Can you help me please?
Did you check the documentation? The flag you want is QIODevice::Append.
I'm trying to read in a file of trace addresses (each on their own line) and append to the front of each. This input file is intended to be the engine of a cache emulator i'm trying to build. I am having issues reading the file in without getting into an infinite loop. When I change the do-while to run on a false condition, I get the proper output for just the do segment. Therefore, I know I'm running into an infinite loop issue with how I worded my while segment. Maybe i'm fatigued and can't see the issue with this function:
void MainWindow::readFile(){
infoLabel->setText(tr("Invoked <b>File|Open</b>"));
QString filename="trace.txt";
QString path = QDir::currentPath();
QFile file("//Users//nathan1324//Desktop//trace.txt");
//file.open(QIODevice::ReadOnly);
if(!file.exists()){
qDebug() << "File cannot be found "<<filename;
qDebug() << " " << path;
}else{
qDebug() << filename<<" Opening...";
}
QString line;
textEdit->clear();
if (file.open(QIODevice::ReadOnly | QIODevice::Text)){
QTextStream stream(&file);
do {
line = stream.readLine();
textEdit->setText(textEdit->toPlainText()+"0x"+line+"\n");
qDebug() << "line: "<<line;
} while (!line.isNull());
}
file.close();
}
Any suggestions of an alternative way to write this function?
To add items use the append function of QTextEdit:
void QTextEdit::append(const QString & text)
Appends a new paragraph with text to the end of the text edit.
Note: The new paragraph appended will have the same character format
and block format as the current paragraph, determined by the position
of the cursor.
To iterate through the QTextStream atEnd()
bool QTextStream::atEnd() const
Returns true if there is no more data to be read from the QTextStream;
otherwise returns false. This is similar to, but not the same as
calling QIODevice::atEnd(), as QTextStream also takes into account its
internal Unicode buffer.
Code:
void MainWindow::readFile(){
infoLabel->setText(tr("Invoked <b>File|Open</b>"));
QString filename = "trace.txt";
QString path = QDir::currentPath();
QFile file("//Users//nathan1324//Desktop//trace.txt");
if(!file.exists()){
qDebug() << "File cannot be found "<<filename;
qDebug() << " " << path;
return;
}
QString line;
textEdit->clear();
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
qDebug() << "Could not open file" << filename;
return;
}
qDebug() << filename<<" Opening...";
QTextStream stream(&file);
while (!stream.atEnd()) {
line = stream.readLine();
if(!line.isNull()){
textEdit->append("0x"+line);
qDebug() << "line: "<<line;
}
}
file.close();
}
Use atEnd to detect the end of a stream:
bool QTextStream::atEnd() const
Returns true if there is no more data to be read from the QTextStream;
otherwise returns false. This is similar to, but not the same as
calling QIODevice::atEnd(), as QTextStream also takes into account its
internal Unicode buffer.
while (!stream.atEnd()) {
line = stream.readLine();
textEdit->setText(textEdit->toPlainText()+"0x"+line+"\n");
qDebug() << "line: "<<line;
}
I'm working on a program that reads a text file of tab delimited doubles and sums up each column, effectively calculating the integral of each column.
What I want to be able to do is choose a specific column to sum up rather than sum all the columns.
The code I've already got working for the integral of all columns:
void MainWindow::on_pushButton_clicked()
{
data::SingleLineData.resize(512);
QString test;
QString inputfile = QFileDialog::getOpenFileName(
this,
tr("Open File"),
"/Users",
"All files (*.*)"
);
if(inputfile != ""){
QFile file(inputfile);
if(!file.open(QFile::ReadOnly)){
}
QTextStream in(&file);
double buffer;
while(!file.atEnd()){
in.readLine();
for(int i=0; i<512; i++){
in >> buffer;
data::SingleLineData[i]+=buffer;
}
}
}
qDebug() << data::SingleLineData;
// ************* file output **************************************************
QString filename = QFileDialog::getSaveFileName(
this,
tr("Save File"),
"/Users",
"Text files (*.txt)"
);
QFile fileout(filename);
if (fileout.open(QFile::ReadWrite | QFile::Truncate)){
QTextStream out(&fileout);
for (QVector<double>::iterator iter = data::SingleLineData.begin(); iter != data::SingleLineData.end(); iter++){
out << *iter <<", ";
}
fileout.close();
}
}
And here is my attempt at choosing out an individual column using an integer input into a spin box:
void MainWindow::on_pushButton_2_clicked()
{
QString inputfile = QFileDialog::getOpenFileName(
this,
tr("Open File"),
"/Users",
"All files (*.*)"
);
QVector<double> SingleChannel;
if (inputfile != ""){
QFile file(inputfile);
if (!file.open(QIODevice::ReadOnly)){
}
QTextStream in(&file);
SingleChannel.resize(1);
double buffer;
int channelnumber = ui->spinBox->value();
while(!file.atEnd()){
in.readLine();
for (int i = 0; i < 512; i++){
in >> buffer;
if (i == channelnumber){
SingleChannel.push_back(buffer);
}
data::SingleLineData[i]+=buffer;
}
}
}
qDebug() << SingleChannel;
}
I get the following error though:
ASSERT failure in QVector<T>::operator[]: "index out of range", file /Users/mduncan/Qt/5.3/clang_64/lib/QtCore.framework/Headers/qvector.h, line 385
The program has unexpectedly finished.
Anyone have any ideas?
Thanks :)
add this line at the beginning of void MainWindow::on_pushButton_2_clicked method
data::SingleLineData.resize(512);
this will resize your container to 512 defaulted value count elements. Because you use data::SingleLineData[i]+=buffer, which need access the i th element in the container.
I have a treeview that displays a folder with text files. There is a 'open' button. That will open the file. But when this button is pressed it should rename the file to: read filename.txt. So if there is a file for example that is name nameslist.txt and the button is pressed it should rename it to read nameslist.txt or something similar. I thought of something like this:
void berichtenhistorie::on_Openbutton_released()
{
QModelIndex index = ui->treeView->currentIndex();
QString name = index.fileName();
QString path = index.filePath();
QFile file(path);
file.open(QIODevice::WriteOnly | QIODevice::Text);
file.rename("read " + name);
file.close();
}
But this isnt working. I get the following error's:
error: C2352: 'QDirModel::fileName' : illegal call of non-static member function
But I dont know how to use fileName() and filePath() correctly.
Thanks for help!
I think that here is what you looking for:
void berichtenhistorie::on_Openbutton_released()
{
QModelIndex index = ui->treeView->currentIndex();
QFileSystemModel *model = (QFileSystemModel*)ui->treeView->model();
QString path = model->filePath(index);
QString name = model->fileName(index);
QString dir = path;
dir.remove(dir.size() - name.size(), name.size());
QFile file(path);
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
//Interact with the file
file.close();
if(file.rename(QString("%1read %2").arg(dir, name)))
qDebug() << "Renamed";
}
}
Here's a break out of each step you'll need to do to work with QFile.
QFile file("test.txt");
if(file.exists())
{
qDebug() << "found file";
if(file.open(QIODevice::ReadWrite))
{
qDebug() << "opened";
if(file.rename("text1.txt"))
{
qDebug() << "renamed";
}
else
{
qDebug() << "failed to rename";
}
file.close();
}
}
else
{
qDebug() << "file does not exist";
}
In the end, you'll only really need your debugger to step through instead of printing out everything known to your application. E.g.
QFile file("test.txt");
if(file.exists() && file.open(QIODevice::ReadWrite))
{
if(file.rename("text1.txt"))
{
qDebug() << "renamed";
}
file.close();
}
I'm currently create an apps in Meego using QML and JS on most of the part. and now I stumbled upon a problem.
From javascript I want to call a C++ function to read text file, parse it, and then return an array of the parsing result.
so I create a Q_INVOKABLE function called parse() and call it through javascript
function parse() {
var myArray = new Array();
myArray = parser.parse("/home/user/MyDocs/angklungtext.txt")
if(myArray === undefined){
console.log("null found");
}
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i][0] + "," + myArray[i][1])
}
}
and here is the parse function in C++
QVariantList* QMLParser::parse(QString filename)
{
qDebug() << "start debugging";
qDebug() << filename;
qDebug() << QDir::currentPath();
QDir dir;
qDebug()<< dir.absoluteFilePath(filename);
QFile file(filename);
if(!file.exists())
{
qDebug() << "File: " << file.fileName() << "tidak ditemukan";
return NULL;
}
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Tidak dapat membuka file" << file.fileName() << "untuk ditulis";
return NULL;
}
QTextStream stream(&file);
QVariantList* myList = new QList<QVariant>;
while(!stream.atEnd())
{
QString line = stream.readLine();
qDebug() << line.trimmed();
QStringList lineList = line.split(":");
myList->append(lineList);
}
file.close();
return myList;
}
sadly.
when I try to run it it giving a result like this
start debugging
"/home/user/MyDocs/angklungtext.txt"
"/home/developer"
"/home/user/MyDocs/angklungtext.txt"
"1:1000"
"4:2000"
"5:3000"
"2:4000"
null found
file:///opt/memoryreader/qml/memoryreader/myjs.js:8: TypeError: Result of expression 'myArray' [undefined] is not an object.
looks like the C++ parse function successfully parsing the file. it can read it and it can save it into the QVariantList.
but after it return the result into javascript myArray still [undefined].
is there something wrong with the conversion?
Just simplify the C++ side like this :
QVariant QMLParser::parse(QString filename)
{
QStringList myList;
qDebug() << "start debugging";
qDebug() << filename;
qDebug() << QDir::currentPath();
QDir dir;
qDebug() << dir.absoluteFilePath(filename);
QFile file(filename);
if(!file.exists()) {
qDebug() << "File: " << file.fileName() << "tidak ditemukan";
return NULL;
}
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "Tidak dapat membuka file" << file.fileName() << "untuk ditulis";
return NULL;
}
QTextStream stream(&file);
while(!stream.atEnd()) {
QString line = stream.readLine();
qDebug() << line.trimmed();
myList << line.trimmed().split(":");
}
file.close();
return QVariant::fromValue(myList);
}
And it should work !
Just remember, QML must see a QVariant, even if a QList is wrapped inside it, and Qt is able to convert most of its base types to QVariant using QVariant::fromValue(T) so use it extensively.
Oh and BTW a QVariant is reference not pointer.
Haven't done this myself, so I'm just thinking out loud. But I note that you're returning a pointer to a QVariantList...which looks suspect. (Also: if you new, then who would do the delete?)
Have you tried returning it by value?