QFile won't open the file - c++

I have a program that I basically stole from the Qt website to try to get a file to open. The program refuses to open anything I am confused as to why. I have looked for lots of documentation but found nothing can you please explain why it does not work.
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QString>
MainWindow::MainWindow(QWidget *parent) :
QWidget(parent)
{
QFile file("C:/n.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&file);
QString f=in.readLine();
lab =new QLabel("error",this);
lab->setGeometry(100,100,100,100);
lab->setText(f);
}

Before opening the file, you can always check the existense:
QFile file("myfile.txt");
if (!file.exists()) {
// react
}
If file exists but does not open, you can get the error state and message:
QString errMsg;
QFileDevice::FileError err = QFileDevice::NoError;
if (!file.open(QIODevice::ReadOnly)) {
errMsg = file.errorString();
err = file.error();
}
And always: if the file was openend, then remember to close it. In your example you didn't:
file.close();

FileError QFile::error () const
Returns the file error status.
The I/O device status returns an error code. For example, if open() returns false, or a read/write operation returns -1, this function can be called to find out the reason why the operation failed.
See also unsetError().
Post the error code. Isn't it supposed to be QFile file("C:\n.txt"); \ not / in windows?

Related

Qt C++ saving a image to a specified folder [duplicate]

It's strange, I add desired file into the resources via Add Existing Files..., the file is there. I run qmake ("Build->Run qmake") to make the file available.
The first issue: I can't write anything into the file from output terminal! But when I manually write into the file, the output terminal shows the change every time I run it. Second issue: it still says QIODevice::read: device not open !
Here's my code:
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <iostream>
void wFile(QString Filename)
{
QFile nFile(Filename);
QTextStream str(&nFile);
qDebug() << "what do you want to write in the desired file: ";
str.readLine();
if (!nFile.open(QFile::WriteOnly | QFile::Text))
{
qDebug() << "could not open the file";
return;
}
nFile.flush();
nFile.close();
}
void read (QString Filename){
QFile nFile(Filename);
if(!nFile.open(QFile::ReadOnly | QFile::Text))
{
qDebug() << "could not open file for reading";
return;
}
QTextStream in(&nFile);
QString nText = in.readAll();
qDebug() << nText;
nFile.close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString nFilename =":/MyFiles/DocumentArminV.txt";
wFile(nFilename);
read(nFilename);
return a.exec();
}
And here's output terminal of the code:
The files saved in a qresource are read-only since they are part of the executable so you can not write or modify them.
docs:
Currently, Qt always stores the data directly in the executable, even on Windows, macOS, and iOS, where the operating system provides native support for resources. ...

Qt, C++ - Editing an existing INI file from project doesn't work when I need to save it [duplicate]

It's strange, I add desired file into the resources via Add Existing Files..., the file is there. I run qmake ("Build->Run qmake") to make the file available.
The first issue: I can't write anything into the file from output terminal! But when I manually write into the file, the output terminal shows the change every time I run it. Second issue: it still says QIODevice::read: device not open !
Here's my code:
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <iostream>
void wFile(QString Filename)
{
QFile nFile(Filename);
QTextStream str(&nFile);
qDebug() << "what do you want to write in the desired file: ";
str.readLine();
if (!nFile.open(QFile::WriteOnly | QFile::Text))
{
qDebug() << "could not open the file";
return;
}
nFile.flush();
nFile.close();
}
void read (QString Filename){
QFile nFile(Filename);
if(!nFile.open(QFile::ReadOnly | QFile::Text))
{
qDebug() << "could not open file for reading";
return;
}
QTextStream in(&nFile);
QString nText = in.readAll();
qDebug() << nText;
nFile.close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString nFilename =":/MyFiles/DocumentArminV.txt";
wFile(nFilename);
read(nFilename);
return a.exec();
}
And here's output terminal of the code:
The files saved in a qresource are read-only since they are part of the executable so you can not write or modify them.
docs:
Currently, Qt always stores the data directly in the executable, even on Windows, macOS, and iOS, where the operating system provides native support for resources. ...

How to write into .ini file using Qt C++? [duplicate]

It's strange, I add desired file into the resources via Add Existing Files..., the file is there. I run qmake ("Build->Run qmake") to make the file available.
The first issue: I can't write anything into the file from output terminal! But when I manually write into the file, the output terminal shows the change every time I run it. Second issue: it still says QIODevice::read: device not open !
Here's my code:
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <iostream>
void wFile(QString Filename)
{
QFile nFile(Filename);
QTextStream str(&nFile);
qDebug() << "what do you want to write in the desired file: ";
str.readLine();
if (!nFile.open(QFile::WriteOnly | QFile::Text))
{
qDebug() << "could not open the file";
return;
}
nFile.flush();
nFile.close();
}
void read (QString Filename){
QFile nFile(Filename);
if(!nFile.open(QFile::ReadOnly | QFile::Text))
{
qDebug() << "could not open file for reading";
return;
}
QTextStream in(&nFile);
QString nText = in.readAll();
qDebug() << nText;
nFile.close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString nFilename =":/MyFiles/DocumentArminV.txt";
wFile(nFilename);
read(nFilename);
return a.exec();
}
And here's output terminal of the code:
The files saved in a qresource are read-only since they are part of the executable so you can not write or modify them.
docs:
Currently, Qt always stores the data directly in the executable, even on Windows, macOS, and iOS, where the operating system provides native support for resources. ...

How to read data using QSerialPort to write to a file using QFile?

New to C++ and Qt, I'm trying to use a microcontroller to send a large set of data (made up of integers and commas) over serial to be put in a .csv file for use in Excel. My mainwindow.cpp code so far (where I've put all the action for testing purposes):
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <string>
#include <QtSerialPort/QSerialPort>
#include <QString>
#include <QTextEdit>
#include <QFile>
#include <QTextStream>
QSerialPort *serial;
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
serial = new QSerialPort(this);
serial->setPortName("/dev/cu.usbmodemfa131");
serial->setBaudRate(QSerialPort::Baud9600);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
serial->open(QIODevice::ReadWrite);
connect(serial, SIGNAL(readyRead()), this, SLOT(serialReceived()));
}
MainWindow::~MainWindow()
{
delete ui;
serial->close();
}
void MainWindow::serialReceived()
{
QString filename = "/Users/me/Documents/myFile/datacollecting.csv";
QFile file(filename);
QTextStream out(&file);
file.open(QIODevice::ReadWrite);
QByteArray ba;
ba = serial->readAll();
out << ba;
file.close();
}
The code however is giving me some issues. It does not work reliably at all and in the resultant file it only stores the last 10 or so (out of several thousand) characters. I have searched around but have not found a way to properly store large chunks of data over serial. Is there a better way to achieve what I'm trying to do above? New to this so any help would be greatly appreciated!
As already written in comments you should open your output file in append mode by adding QIODevice::Append flag so that all data is written to the end of the file.
You can also connect to error signal where you can inspect possible errors. See serial port enums here.
connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(handleError(QSerialPort::SerialPortError)));
void MainWindow::handleError(QSerialPort::SerialPortError error)
{
...
}

Issue with deleting text in file

Explaining of my purpose:
my program have two section first reading two word from user(second word is meaning of first one) and save this words in two text file second section is showing or deleting words as desire of user.
What is my issue?:
my program works perfectly but after days will something like this happen:
when i try to delete two words from .txt files(i mean 1 word with meaning of it) first word will delete but second word(meaning) will not delete, it sounds like .txt file corrupted only thing that will fix every thing is delete that text file and create new one and thats very annoying that means lose all informations
note: first word and second word are in separate files. second words are still able to show.
what did i try?:
i try to check that is second word text file open or closed. that sounds like it will open or close in right time.
check that if text file is read-only. that wasnt.
i dont know what really happening here :( !!!!
here its my delete code am i missing something ?
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <fstream>
#include <QFile>
#include <QTextStream>
#include <QIODevice>
#include <QDebug>
#include <QMessageBox>
#include <QProcess>
#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
void newFunc();
void restartApp();
void makeFa();
int xy=-1;
ifstream sfile("en.txt");
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
newFunc();
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void newFunc(){
QFile check("EnTemp.txt");
if(check.exists()){
}
else{
ofstream EnTemp("EnTemp.txt");
}
}
void restartApp()
{
qApp->quit();
QProcess::startDetached(qApp->arguments()[0], qApp->arguments());
}
void MainWindow::on_Enter_clicked()
{
if((ui->InEN->text().isEmpty()) || (ui->InFa->text().isEmpty())){
QMessageBox msg;
msg.setText("Fields are empty");
msg.exec();
}
else{
QString en,fa;
en=ui->InEN->text();
fa=ui->InFa->text();
// saving EN words
QFile dataE("en.txt");
dataE.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream streamE(&dataE);
streamE<<en<<"\r\n";
dataE.close();
// saving FA words
QFile DataF("fa.txt");
DataF.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream streamF(&DataF);
streamF.setCodec("UTF-8");
streamF<<fa<<"\r\n";
DataF.close();
ui->InEN->clear();
ui->InFa->clear();
}
}
void MainWindow::on_Next_clicked()
{
QFile EnTemp("EnTemp.txt");
EnTemp.open(QIODevice::WriteOnly);
QTextStream GetTemp(&EnTemp);
if(!sfile.eof()){
string get;
getline(sfile,get);
ui->ShowEn->setText(QString::fromStdString(get));
ui->ShowFa->clear();
xy++;
GetTemp<<xy;
EnTemp.close();
}
else{
restartApp();
}
}
void MainWindow::on_mean_clicked()
{
cout<<xy;
QFile openFa("fa.txt");
QString getFa;
openFa.open(QIODevice::ReadWrite);
QTextStream pointfa(&openFa);
pointfa.setCodec("UTF-8");
int forword=0;
while(forword<=xy){
getFa=pointfa.readLine();
forword++;
}
ui->ShowFa->setText(getFa);
openFa.close();
}
void MainWindow::on_delete_2_clicked()
{
makeFa();
ofstream tempE;
if(!ui->ShowEn->text().isEmpty() | !ui->ShowFa->text().isEmpty())
{
QMessageBox msg;
int ret;
msg.setText("Are you sure you want to delete this words?");
msg.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msg.setIcon(QMessageBox::Warning);
ret= msg.exec();
switch(ret){
case QMessageBox::Yes:
QString input;
input=ui->ShowEn->text();
string line;
ifstream DataE;
DataE.open("en.txt");
tempE.open("tempE.txt");
while(getline(DataE,line)){
if(line != input.toStdString()){
tempE<<line<<"\r\n";
}
}
QString inputF;
inputF= ui->ShowFa->text();
string lineF;
ifstream DataF;
ofstream tempF("tempF.txt");
DataF.open("fa.txt");
while(getline(DataF, lineF)){
if( lineF != inputF.toStdString()){
tempF<<lineF<<"\r\n";
}
}
DataE.close();
DataF.close();
tempE.close();
tempF.close();
sfile.close();
remove("en.txt");
remove("fa.txt");
rename("tempE.txt", "en.txt");
rename("tempF.txt", "fa.txt");
break;
}
}
else{
QMessageBox mass;
mass.setText("Fields are empty");
mass.exec();
}
restartApp();
}
void MainWindow::on_Restore_clicked()
{
xy= 0;
int reach=0;
string get;
QString s;
ifstream openTemp("EnTemp.txt");
openTemp>>xy;
while(reach<=xy){
getline(sfile,get);
reach++;
}
ui->ShowEn->setText(QString::fromStdString(get));
}
void makeFa(){
QFile tempF;
tempF.setFileName("tempF.txt");
tempF.open(QIODevice::ReadWrite | QIODevice::Append);
QTextStream stream(&tempF);
stream.setCodec("UTF-8");
tempF.close();
}
I'm on windows 8.1
i notice something new right now when i try to delete all information in second .txt file the size of file will be 3 bytes instead of 0 bytes
3 bytes for an otherwise empty file might match the UTF-8 BOM (not saying it is without knowing said bytes, but it is a strong hint). Your delete function might be fine (althought you should make the file filtering another function for clarity, and DRY), but would work only with ascii charset since you're relying on std::i/ofstream and std::string.
It might be (again, no certitude, just a wild guess) that you're creating a file with QFile, and that you put a "meaning" containing non-ascii characters and thus QFile automatically converts the file to an UTF-8 prefixed with BOM.
Would you mind updating your post with the file creation/update methods if you're uncertain of this lead?
[Edit] The other option would be that you're writing non ascii characters with ofstream which would probably lead to the "meaning" not being found, and thus the file being fully replicated.