ifstream sets failbit on declaration - ifstream

I don't really understand why this is happening at all. I'm trying to open a file to read some data into my program but failbit gets set instantly, having moved error messages around it seems that failbit actually gets set before I even attempt input.open(). The undeclared variables in the code are globals which live elsewhere (messy but will refine later) Here's the offending function from a larger project:
int read_input()
{
ifstream input;
string value;
int file_complete=0;
int count=0;
if(input.failbit)
printf("Really?\n");
input.clear();
input.open("Input.txt");
while(!file_complete)
{
if(input.failbit)
{
printf("Reading in set-up value number %d failed.", count+1);
getchar();
return 1;
}
else if(input.eofbit)
{
file_complete=1;
}
if(input.get()=='=')
{
getline(input, value);
switch(count)
{
case 0:
n_loci=atoi(value.c_str());
count++;
break;
case 1:
n_founders=atoi(value.c_str());
count++;
break;
case 2:
n_self=atoi(value.c_str());
count++;
break;
// Add more cases later
}
}
}
input.close();
return 0;
}
This program for me turns out:
Really?
Reading in set-up value number 1 failed.
I'm assuming I've done something very stupid but have been at this quite a while now.
P.S I'm compiling with the latest version of g++ on cygwin on top of Windows 7.

OK fixed this myself now:
Failbit seems to be set by EOFs in some implementations so instead I switched to using input.good() and consequently all was good.
There was also some logical error in my program with the checking for "=" part too as ifstream.get() returns it's value as an integer so I needed to cast them back into chars for comparison.

Related

QTextStream - What exactly does the position method return

I have a question about what a QTextStream is calculating with the pos() method. I assumed it was the number of bytes, but it seems that this might not be the case.
The reason I ask, is that I am processing rows in a file, and once the number of rows read reached some arbitrary number or stream.atEnd() is true, I break out of the loop and save stream.pos() to a qint64* variable. Once the processing is complete, I go back to the file and seek(*filePosition) to get back to my last position and grab more data until stream.atEnd() is true. This works in the sense that can keep track of where I am, but it is very slow calling stream.pos() as is noted in the Qt docs.
What I am attempting is to update the file position after each line is read in an efficient manner. However, it is not working and when the program goes back to read the file again, the position is not correct as the first line it reads starts in the middle of line previously read on the last iteration.
Here is what is have so far:
QTextStream stream(this);
stream.seek(*filePosition);
int ROW_COUNT = 1;
while (!stream.atEnd()) {
QString row = stream.readLine();
QStringList rowData = row.split(QRegExp(delimiter));
*filePosition += row.toUtf8().size();
/*
processing rowData...
*/
if (ROW_COUNT == ROW_UPLOAD_LIMIT) {
break;
}
ROW_COUNT++;
}
/*
close files, flush stream, more processing, etc...
*/
QTextStream::pos returns position in bytes. I see the following problems:
You are not accounting for the line ending character (or 2 characters)
In UTF-8, a single character might take more than 1 byte
Also, why save buffer position after reading each line? This might be faster:
if (ROW_COUNT == ROW_UPLOAD_LIMIT) {
*filePosition = stream.pos();
break;
}
The solution was to create the QTextStream outside of the function and pass it in as a parameter. Doing this allows me to not have to worry about tracking the position on each iteration because I keep the stream in scope until I have completely finished processing the file.
class FeedProcessor {
...
void processFeedFile() {
IntegrationFile file("big_file.txt");
file.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream stream(&file);
while(!stream.atEnd()) {
file.extractFileContents(&stream);
/*
do more processing with file
*/
}
}
...
}
class IntegrationFile : public QFile {
...
void extractFileContents(QTextStream* stream) {
int ROW_COUNT = 1;
while (!stream.atEnd()) {
QString row = stream.readLine();
QStringList rowData = row.split(QRegExp(delimiter));
/*
processing rowData...
*/
if (ROW_COUNT == ROW_UPLOAD_LIMIT) {
break;
}
ROW_COUNT++;
}
/*
close files, flush stream, more processing, etc...
*/
}
...
}

Error passing pointer in QT

In QT have the following code that starts a thread to send out commands. The thread takes a char * and int as arguments. In the "run" I use the pointer that is given by the constuctor. The code is:
MyThread::MyThread(char * payld, int payld_size)
{
payload_size = payld_size;
payload_p = payld;
}
void MyThread::run()
{
while(...)
{
sendCommand(payload_p, payload_size);
}
}
Unfortunately this doesn´t work and my application crashes when I try to use thread.start(). But when I change it to:
MyThread::MyThread(char * payld, int payld_size)
{
payload_size = payld_size;
payload_p = payld;
for(int i=0; i<payload_size; i++)
{
payload[i] = payld[i];
}
}
void MyThread::run()
{
while(...)
{
sendCommand(payload, payload_size);
}
}
The code does run and only crashes sometimes (looks pretty random to me). Can anybody Explain me why version one doesnt work and version two does? And any ideas on why the second code sometimes crashes? Could it be because the size of payload is not predefined (in the header file I defined it as
char payload[];
When I define it as:
char payload[10];
it seems to work better, but it is annoying to test since the crashes are pretty random.
instead of fiddling with char*, I would switch to QString (since you're using Qt). It takes a bit of learning, but it's almost mandatory to get code working smoothly in this framework. Then declare
QString payload;
and depending on sendCommand implementation, use one of the member functions QString to get the char*, like payload.toLatin1()

QList for touch-points not being created, "A data abort exception has occurred"

I am trying to get touch inputs for my program targeting an N8 (and a C7), and I am not able to create a QList for keeping touchpoints using QTouchEvent::touchPoints(). The program crashes with the following line: Thread has crashed: A data abort exception has occurred accessing 0xee
The overloaded events function looks like:
bool GLWindow::event(QEvent *event)
{
switch ( event->type() ) {
case QEvent::TouchBegin: {
QList<QTouchEvent::TouchPoint> touchBeginPoints =
static_cast<QTouchEvent *>(event)->touchPoints();
foreach (const QTouchEvent::TouchPoint &touchBeginPoint, touchBeginPoints)
{
float touchBeginX = touchBeginPoint.pos().x();
float touchBeginY = touchBeginPoint.pos().y();
qDebug() << "touchBeginPoint := " << touchBeginX << ", " << touchBeginY;
}
break;
}
case QEvent::TouchUpdate: {
// same as touch begin: getting touch point
break;
}
case QEvent::TouchEnd: {
// same as touch begin: getting touch point
break;
}
default: {
qDebug() << "Goodbye";
return true;
}
}
return true;
}
Now,
I have never worked with containers before. But creating and using a QList in another part of the program works fine. Should I be including something in my .pro file? (Most problems seem to end up regarding this with me!)
I read (a bit) about exceptions in Qt and Symbian, but I am not able to get most of that. BUT I am not doing any networking or resource based i/o or manipulation except textures for 3D objects. Is it possible that memory allocation while running the program is creating some problem?
Basically I am just trying to print the touch point. But I am clueless as to why I can’t create a QList. The code compiles fine. I tried my best (unsuccessfully), but is there any other way to get the screen coordinates of a touchpoint (one that does not require a QList)? Any comments are welcome.
[Reposting from qt-project.org.]
Your syntax is 100% correct. Just look at this example: http://www.developer.nokia.com/Community/Wiki/Painting_in_Qt
What I'm guessing happens is that QTouchEvent::touchPoints() returns a list big enough that it overflows your stack. Try increasing the stack size for your application.
Is your syntax correct ? The compilation error seems to reinforce teukkam point...
What happens when you replace
static_cast<QTouchEvent *>(event)->touchPoints()
With
(dynamic_cast<QTouchEvent *>(event))->touchPoints()
Notice the parentheses...

Unix Networking Programming - Client and Server. List Function That wait for input after 40 lines

I am currently in the process of making a Client and Server in the Unix/Windows environment but right now I am just working on the Unix side of it. One of the function we have to create for the program is similar to the list function in Unix which shows all files within a dir but we also have to show more information about the file such as its owner and creation date. Right now I am able to get all this information and print it to the client however we have to also add that once the program has printing 40 lines it waits for the client to push any key before it continues to print.
I have gotta the program to sort of do this but it will cause my client and server to become out of sync or at least the std out to become out of sync. This means that if i enter the command 'asdad' it should print invalid command but it won't print that message until i enter another command. I have added my list functions code below. I am open to suggestions how how to complete this requirement as the method I have chosen does not seem to be working out.
Thank-you in advance.
Server - Fork Function: This is called when the list command is enter. eg
fork_request(newsockfd, "list", buf);
int fork_request(int fd, char req[], char buf[])
{
#ifndef WIN
int pid = fork();
if (pid ==-1)
{
printf("Failed To Fork...\n");
return-1;
}
if (pid !=0)
{
wait(NULL);
return 10;
}
dup2(fd,1); //redirect standard output to the clients std output.
close(fd); //close the socket
execl(req, req, buf, NULL); //run the program
exit(1);
#else
#endif
}
Here is the function used to get all the info about a file in a dir
void longOutput(char str[])
{
char cwd[1024];
DIR *dip;
struct dirent *dit;
int total;
char temp[100];
struct stat FileAttrib;
struct tm *pTm;
int fileSize;
int lineTotal;
if(strcmp(str, "") == 0)
{
getcwd(cwd, sizeof(cwd));
}
else
{
strcpy (cwd, str);
}
if (cwd != NULL)
{
printf("\n Using Dir: %s\n", cwd);
dip = opendir(cwd);
if(dip != NULL)
{
while ((dit = readdir(dip)) != NULL)
{
printf("\n%s",dit->d_name);
stat(dit->d_name, &FileAttrib);
pTm = gmtime(&FileAttrib.st_ctime);
fileSize = FileAttrib.st_size;
printf("\nFile Size: %d Bytes", fileSize);
printf("\nFile created on: %.2i/%.2i/%.2i at %.2i:%.2i:%.2i GMT \n", (pTm->tm_mon + 1), pTm->tm_mday,(pTm->tm_year % 100),pTm->tm_hour,pTm->tm_min, pTm->tm_sec);;
lineTotal = lineTotal + 4;
if(lineTotal == 40)
{
printf("40 Lines: Waiting For Input!");
fflush(stdout);
gets(&temp);
}
}
printf("\n %d \n", lineTotal);
}
else
{
perror ("");
}
}
}
At here is the section of the client where i check that a ! was not found in the returned message. If there is it means that there were more lines to print.
if(strchr(command,'!') != NULL)
{
char temp[1000];
gets(&temp);
}
Sorry for the long post but if you need anything please just ask.
Although, I didn't see any TCP/IP code, I once had a similar problem when I wrote a server-client chat program in C++. In my case, the problem was that I didn't clearly define how messages were structured in my application. Once, I defined how my protocol was suppose to work--it was a lot easier to debug communication problems.
Maybe you should check how your program determines if a message is complete. In TCP, packets are guaranteed to arrive in order with no data loss, etc. Much like a conversation over a telephone. The only thing you have to be careful of is that it's possible to receive a message partially when you read the buffer for the socket. The only way you know to stop reading is when you determine a message is complete. This could be as simple as two '\n' characters or "\n\r".
If you are using UDP, then that is a completely different beast all together (i.e. messages can arrive out of order and can be lost in transit, et cetera).
Also, it looks like you are sending across strings and no binary data. If this is the case, then you don't have to worry about endianess.

Scintilla (QScintilla) 3rd marker define fails

In my class I attempt to define 3 markers, one for errors, one for warnings, and one for breakpoints. This worked well when I was only attempting to define 2 markers, but for some reason the third of these markers doesn't appear when added to a line. If you switch the ordering of the definitions, it is always the third one that fails to appear when markerAdd() is called. The pixmaps are valid, and Scintilla's return values appear to be correct for both defining and adding markers. This is more of a general Scintilla question rather than a QScintilla question I believe, because QScintilla simply does some checks before calling the underlying scintilla code. I have no idea where to even begin in debugging this code. If anyone can shed some light on this, whether it is a known scintilla quirk or it is my fault, I would be eternally grateful.
m_errorIndicator = ui_editor->markerDefine(QPixmap(":/sourcefile/icon_set/icons/bullet_red.png"));
m_breakIndicator = ui_editor->markerDefine(QPixmap(":/sourcefile/icon_set/icons/bullet_black.png"));
m_warningIndicator = ui_editor->markerDefine(QPixmap(":/sourcefile/icon_set/icons/bullet_yellow.png"));
void SourceFile::on_actionAddBreakpoint_triggered()
{
qWarning() << "Added breakpoint to " << m_currentLine;
qWarning() << ui_editor->markerAdd(m_currentLine, m_breakIndicator);
m_breakpoints.append(m_currentLine);
}
void SourceFile::on_actionRemoveBreakpoint_triggered()
{
ui_editor->markerDelete(m_currentLine, m_breakIndicator);
m_breakpoints.removeAll(m_currentLine);
}
void SourceFile::clearProblems()
{
ui_editor->markerDeleteAll(m_errorIndicator);
ui_editor->markerDeleteAll(m_warningIndicator);
}
void SourceFile::markProblems(const QStringList& errors, const QStringList& warnings)
{
foreach(const QString& error, errors) {
int line = error.section(":", 1, 1).toInt();
if(--line < 0) continue;
ui_editor->markerAdd(line, m_errorIndicator);
}
foreach(const QString& warning, warnings) {
int line = warning.section(":", 1, 1).toInt();
if(--line < 0) continue;
ui_editor->markerAdd(line, m_warningIndicator);
}
}
There should be a yellow bullet next to the printf statement. If the warning and breakpoint definitions are switched, the yellow bullet will show up and the black bullet will disappear.
Aha! After days of looking, I finally found the problem.
ui_editor->setMarginMarkerMask(1, m_breakpointMarker);
Was being called in a setup method, which was causing funky behavior. Removing this fixed everything.

Resources