what i want is grab the string until EOF,
Your original code doesn't do that. Your fgets() call reads up to 20 bytes (including a terminating NUL) from the current location in the file until terminated by the EOL or EOF. So, you might get 20 bytes that don't reach the end of anything, you might get less than 20 bytes reaching the end-of-line or end-of-file.
What you asked for:
i've made a seek inside a text file and now i need to grab ONLY the last 20 chars inside the file
Try this program:
#include <QtCore>
#include <QDebug>
#include <cstdio>
int main(int argc, char *argv[])
{
// Your code
FILE *kidboot;
char ruta[20];
kidboot=fopen("test.txt","r");
fseek(kidboot,66,SEEK_SET);
fgets(ruta,20,kidboot);
fclose(kidboot);
qDebug("Your result: \"%s\"", ruta);
// what your code does
qint64 fileSize = info.size();
if (file.seek(66)) {
ba = ba.left(19);
qDebug("This result: \"%s\"", ba.data());
}
else
qWarning() << "File seek failed";
file.close();
}
else
qWarning() << "File too short";
// what you asked for
if (file.seek(fileSize - 20))
qDebug() << "Last 20:" << file.readAll();
else
qWarning() << "File seek failed";
file.close();
}
else
qWarning() << "File too short";
return 0;
}
#include <QtCore>
#include <QDebug>
#include <cstdio>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
// Your code
FILE *kidboot;
char ruta[20];
kidboot=fopen("test.txt","r");
fseek(kidboot,66,SEEK_SET);
fgets(ruta,20,kidboot);
fclose(kidboot);
qDebug("Your result: \"%s\"", ruta);
// what your code does
QFile file("test.txt");
QFileInfo info(file);
qint64 fileSize = info.size();
if (fileSize >= 66 && file.open(QIODevice::ReadOnly | QIODevice::Text)) {
if (file.seek(66)) {
QByteArray ba = file.readLine();
ba = ba.left(19);
qDebug("This result: \"%s\"", ba.data());
}
else
qWarning() << "File seek failed";
file.close();
}
else
qWarning() << "File too short";
// what you asked for
if (fileSize >= 20 && file.open(QIODevice::ReadOnly | QIODevice::Text)) {
if (file.seek(fileSize - 20))
qDebug() << "Last 20:" << file.readAll();
else
qWarning() << "File seek failed";
file.close();
}
else
qWarning() << "File too short";
return 0;
}
To copy to clipboard, switch view to plain text mode
with this test.txt file to see the difference:
The quick brown fox jumps over the lazy dog a couple of times to make this
long enough.
0 1 2 3 4 5 6 7
01234567890123456789012345678901234567890123456789012345678901234567890123456789
The quick brown fox jumps over the lazy dog a couple of times to make this
long enough.
0 1 2 3 4 5 6 7
01234567890123456789012345678901234567890123456789012345678901234567890123456789
To copy to clipboard, switch view to plain text mode
Bookmarks