PDA

View Full Version : Program crashes while trying to do a check in constructor



hakermania
31st August 2010, 18:03
Hi, I have 2 .ui files. One is the main and the other is the preferences window(this is actually a QDialog). In the constructor of the preferences window i have added this code to check if the second line of a file contains the char "1". Unfortunately then the program craches (this is the reason for sure, because when I comment this piece of source then it works fine...
This is the source:

char homee[150]="/home/";
strcat(homee,py); //py is the current logged on user
char otherr[100]="/.config/on_launch_enabled_options";
strcat(homee,otherr);
char line [ 128 ];
int i;
FILE *file = fopen ( homee, "r" );
for ( i = 0; i < 1; ++i )
{
fgets ( line, sizeof line, file ); }
fclose ( file );
if(!strcmp (line,"1\n"))
ui->checkminimizeonlaunch->setCheckState(Qt::Checked); else ui->checkminimizeonlaunch->setCheckState(Qt::Unchecked);
Thx for any replies. :)
Notice that if I do the same thing in a Qt-console application it works fine
(changing ui->checkminimizeonlaunch->setCheckState(Qt::Checked); else ui->checkminimizeonlaunch->setCheckState(Qt::Unchecked); to cout << "Strings Are similar\n"; )

It crushes exactly at the point it says fgets ( line, sizeof line, file );

tbscope
31st August 2010, 19:12
The file pointer will not be valid.

Before using pointers, always check if they are valid.

hakermania
31st August 2010, 21:30
You are right. After a check the file pointer is not valid.
http://a.imageshack.us/img814/4397/screenshot3y.png
http://a.imageshack.us/img718/1881/screenshot4bm.png
So, should I simply change the name of the pointer?

tbscope
1st September 2010, 03:38
I don't know what you mean by name of the pointer. The filename, or the object name?

file = 0 because there's a problem opening the file:


RETURN VALUES
Upon successful completion fopen(), fdopen(), and freopen() return a FILE
pointer. Otherwise, NULL is returned and the global variable errno is
set to indicate the error.


Use errno to see which error occured.
http://www.manpagez.com/man/3/fopen/

And print out the exect file path that you're trying to open, maybe there's something wrong with it.

SixDegrees
1st September 2010, 07:46
It isn't just pointers. When a routine can fail, you need to check status upon return before proceeding. In this case, you're trying to open a file - an operation that is not guaranteed to succeed. The filename may be wrong; permissions may not allow you to open the file; the disk the file is on my not be mounted; just to name a few of the possible failure modes.

hakermania
1st September 2010, 10:15
In a very strange way the program now works fine. i can't understand why but errno returned Success and the Preferences dialog opened normally. Anyway, thx for the help!