user3874443
user3874443

Reputation:

Path is wrong, what to do?

I'd like to write something to my path.

My code is following

QString Log::logPacketsPath = QDir::currentPath() + "/logs/Packets/";
int userID = 1;
QString text = "test 1 2 3";


QFile logPacketFile(logPacketsPath + "UserID: " + userID + " - " +  QDateTime::currentDateTime().toString("dd.MM.yy") + ".log");

if (logPacketFile.open(QFile::WriteOnly | QFile::Text | QFile::Append))
{
    QTextStream out(&logPacketFile);
    out << "[" << QDateTime::currentDateTime().toString("dd.MM.yy, hh:mm:ss") << "]: " << text << "\n";
    logPacketFile.close();
}

But it only creates the file named "UserID" with nothing in it.

Do you know where the mistake is?

Upvotes: 1

Views: 89

Answers (2)

huysentruitw
huysentruitw

Reputation: 28151

I'm not sure which OS you're using, but ':' is invalid in a Windows filename.

Next, you should flush the QTextStream before closing the file:

out.flush();
logPacketFile.close();

or create additional scope:

{
    QTextStream out(&logPacketFile);
    out << "[" << QDateTime::currentDateTime().toString("dd.MM.yy, hh:mm:ss") << "]: " << text << "\n";
}
logPacketFile.close();

Also, as Chemobyl has pointed out, you can get into trouble by concatinating the int userID to your filepath. I'd suggest using string formatting to create the filename:

QString logPacketFile("%1UserID%2 - %3.log")
         .arg(logPacketsPath)
         .arg(userID)
         .arg(QDateTime::currentDateTime().toString("dd.MM.yy"));

Upvotes: 2

Jablonski
Jablonski

Reputation: 18524

Convert int to QString:

Use QString::number().

Output with your current code:

"C:/.../logs/Packets/UserID [bad symbols here] - 17.11.14.log" 

Output with

QFile logPacketFile(logPacketsPath + "UserID " + QString::number(userID) + " - " +  QDateTime::currentDateTime().toString("dd.MM.yy") + ".log");//removed colon

is:

"C:/.../logs/Packets/UserID 1 - 17.11.14.log" 

It is source of big troubles. See next:

int userID = 70;
QString text = "test 1 2 3";
QFile logPacketFile(logPacketsPath + "UserID " + userID + " - " +  QDateTime::currentDateTime().toString("dd.MM.yy") + ".log");

Output:

.../UserID F - 17.11.14.log" 

Note F, not a 70 because operator+ thought that you use simple char and 70 in char is F:

http://www.asciitable.com/

So I strongly suggest you to use QString::number to prevent errors.

Upvotes: 0

Related Questions