How to pass boolean from one function to another - c++

I have a program where in function 1 I want to send a boolean value to another function.
Function 1
bool Widget::openFile(){
fileName = QFileDialog::getOpenFileName(this,
"Choose Software File",
"C://",
tr("BIN(*.bin);; All files(*.*)")
);
bool fileExists = QFile::exists(fileName);
return fileExists;
Even if bool is "true" I always get false in function 2.
Function 2
void Widget::on_downloadButton_clicked(bool fileExists)
{
if (fileExists){
qDebug() << "there is a file";
}
else{
qDebug() << "there is no file!";
}
}
No matter what I do I ALWAYS get "there is no file" in function 2. Why is this?
I am expecting to get the same boolean value in Function 2 that is being set in Function 1.

void Widget::on_downloadButton_clicked()
{
if (openFile()){//call here bool function
qDebug() << "there is a file";
}
else{
qDebug() << "there is no file!";
}
}
you can try to call bool function in if statment

Related

Crash when removing a QTemporaryFile

I convert QFile into FILE* to use some third-part libraries. Here is code:
QTemporaryFile pack200_file;
//Here write something into pack200_file
......
pack200_file.seek(0);
int handle_in = pack200_file.handle();
if (handle_in == -1)
{
qCritical() << "Error reopening " << pack200_file.fileName();
return false;
}
FILE * file_in = fdopen(handle_in, "r");
if(!file_in)
{
qCritical() << "Error reopening " << pack200_file.fileName();
return false;
}
QTemporaryFile qfile_out;
if(!qfile_out.open())
{
qCritical() << "Error opening " << qfile_out.fileName();
return false;
}
int handle_out = qfile_out.handle();
if (handle_out == -1)
{
qCritical() << "Error opening " << qfile_out.fileName();
return false;
}
FILE * file_out = fdopen(handle_out, "w");
if (!file_out)
{
qCritical() << "Error opening " << qfile_out.fileName();
return false;
}
try
{
unpack_200(file_in, file_out);
}
catch (std::runtime_error &err)
{
qCritical() << "Error unpacking " << pack200_file.fileName() << " : " << err.what();
return false;
}
//success
QString finalJarname = .....;
QFile::remove(finalJarname);
QFile::copy(qfile_out.fileName(), finalJarname);
fclose(file_in);
fclose(file_out);
qfile_out.remove(); //Here I got crash
pack200_file.remove();
return true;
I got crash at the line qfile_out.remove();, It seems the remove operation cause it. But I got nothing from trace stack and visual studio do not mention me which code trigger the crash finally.
If I change the code into:
fclose(file_in);
fclose(file_out);
qfile_out.setAutoRemove(false);
pack200_file.setAutoRemove(false);
qfile_out.close();
pack200_file.close();
return true;
it will also crash when return ;
Then I change IDE into QtCreator, it said:
Second Chance Assertion Failed: File
f:\dd\vctools\crt\crtw32\lowio\close.c , Line 47
Expression: (_osfile(fh) & FOPEN)
But I can't find the file f:\dd\vctools\crt\crtw32\lowio\close.c.
How can I localize the source of the crash?
You closed qfile_out's file for it with fclose(). Looks like the Visual C runtime library didn't like that, hence the exception. Suggest you remove the calls to fclose... or avoid mixing Qt and non-Qt file operations.

C++ File input works once, but not twice for the same file

So I am running a program that has the users input a command. I have a text file with a list of acceptable command words. I open the file first to make sure that what the user input is indeed a valid command, but after that step I close the file. After that, I use some if/else statements to run a function corresponding to the command. One command is to list all of the valid commands, which requires me to open the file again and simply output the contents. At this step, however, the program simply outputs nothing. Here is the code:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
void mainMenu();
void comJunc(string comString);
void comList();
bool isCommand(string comString);
int main()
{
mainMenu();
return 0;
}
void mainMenu()//This function inputs a command
{
string comString;
bool isCom = false;
cout << endl;
cout << "||Welcome to the main menu||\n\nPlease enter a command. For a list of commands type \"comlist\"\n";
do
{
cout << ">";
cin >> comString;//Input command "comlist"
isCom = isCommand(comString);//Checks if command is valid
if(isCom == false)
cout << endl << "**Error** Command \"" << comString << "\" was not found. Type \"comlist\" for help\n";
}while(isCom == false);
comJunc(comString);
return;
}
bool isCommand(string comString)
{
bool sFlag = false;
string inString;
ifstream comFile;
if(comFile.is_open() == false)
{
comFile.open("commands.txt");
}
while(getline(comFile, inString))
{
if(comString == inString)
sFlag = true;
}
comFile.close();
return sFlag;
}
void comJunc(string comString)//Executes function based on command
{
//comlist, continue, start, customize, exit
if(comString == "comlist")
{
comList();//Calles comList function
}
else if(comString == "exit")
{
//does nothing (exits)
}
else
cout << "Error in comJunc";
return;
}
void comList()
{
string inString;
ifstream comFile;
if(comFile.is_open() == false)
{
comFile.open("command.txt");
}
while(getline(comFile, inString))//This loop is not executed
{
cout << "Random text";//Text is not displayed
cout << endl << inString;
}
cout << endl;
comFile.close();
return;
}
The console looks like this:
||Welcome to the main menu||
Please enter a command. For a list of commands type "comlist"
>
At which point I type "comlist"
The desired result is for the command.txt file to output its contents. It should look like this:
comlist
command2
command3
command4
command5
Instead, the screen is left blank and the program exits as usual.
Any help would be greatly appreciated. Thanks.

After closing the file, I do not have access to it

I use this code in a multithreaded program:
class A{
public:
FILE *File;
bool ThFunc(){
if (CreateDataFile())
std::cout << "File was created\n";
else{
std::cout << "Can't create file\n";
return false;
}
//work with file
if (CloseDataFile()){
std::cout << "File was closed\n";
return true;
}
else{
std::cout << "Can't close file\n";
return false;
};
};
bool CreateDataFile(){
File = fopen ("binary_file.bin", "wb");
if (File!=NULL)
return true;
else
return false;
};
bool CloseDataFile(){
int t=fclose(File);
if (t!=0)
return false;
else{
//insert the file name in another thread
return true;
}
}
};
Sometimes, in another thread (~every 10 files) there is an error: "The file is used by another program(my.exe)", but in console i see: "File was closed". What could be wrong? Mutex is locked, before use a ThFunc() and unlocked after.

Qt Qvariantlist conversion into javascript array unsuccessful

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?

c++ sprintf function and fstream to create/check a text file

I am having some trouble with sprintf and fstream functions in order to create new text files for a POS program/check whether the file already exists. I don't know if i am doing something wrong because the same set of functions works fine in other places in my code...
This particular section of code is taking input from the user to create a details file, the name is made up of the first and last name details that were entered into the system. For some reason the new file is not being created. When I step through the program I can see that the custDetC variable is being filled with the correct data. I have also included the file existence check as it may or may not have something to do with the issue at hand...
Tony Mickel
sprintf(custDetC,"%s%s.txt", firstName.c_str(), lastName.c_str());
cout << custDetC << endl;
FileEX = FileExists(custDetC);
if (FileEX == true)
{
fopen_s(&custDetF,custDetC, "rt");
fprintf(custDetF, "%s %s\n", firstName, lastName);
fprintf(custDetF, "$d\n", phoneNo);
fprintf(custDetF, "%s $s\n", unitHouseNum, street);
fprintf(custDetF, "%s %s %d", suburb, state, postCode);
fclose(custDetF);
}
else
{
char *buf = new char[100];
GetCurrentPath(buf);
cout << "file " << custDetC << " does not exist in " << buf << endl;
}
}
bool FileExists(char* strFilename)
{
bool flag = false;
std::fstream fin;
// _MAX_PATH is the maximum length allowed for a path
char CurrentPath[_MAX_PATH];
// use the function to get the path
GetCurrentPath(CurrentPath);
fin.open(strFilename, ios::in);
if( fin.is_open() )
{
//cout << "file exists in " << CurrentPath << endl;
flag = true;
}
else
{
//cout << "file does not exist in " << CurrentPath << endl;
flag = false;
}
fin.close();
return flag;
}
You seem to be opening the file for reading, but you need to open it for writing.
Instead of "rt" use "wt" in fopen_s()