Access to .h and .cpp files - qt

I am trying to access .h and .cpp files in a selected folder. My goal is to find and print on MainWindow how many lines in .h and .cpp files. In my code, there is no problem to access to selected folder. But for example, what if a .txt file is in this folder, I do not want to count lines of .txt file. My code is here:
int countLine::funcCountLines(QString fullPath)
{
int counter = 0;
QFile file(fullPath);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
return 0;
}
while(!file.atEnd())
{
QByteArray line = file.readLine();
counter++;
}
return counter;
}
Best regards!

You can use QDir::setNameFilters to retrieve only the files you are interested in.
QDir dir;
dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
// Only find .h and .cpp files
QStringList filters;
filters << "*.cpp" << "*.h";
dir.setNameFilters(filters);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
funcCountLines(fileInfo.fileName());
}

Related

QFile error : device not open

I have a code:
int actualSize = 8;
QFile tableFile("C:\\Users\\Ms\\Documents\\L3\\table"+QString::number(actualSize)+".txt");
QTextStream in(&tableFile);
QString oneLine;
oneLine.append(in.readAll());
if(tableFile.exists())
{
messageLabel->setText(oneLine);
}else
{
messageLabel->setText("Not open");
}
In the C:\Users\Ms\Documents\L3\ folder, I have a "table8.txt" file. But the messageLabel (which is a QLabel) will have a "Not open" text, oneLine is empty, tableFile.exists() is false, and I got a device not open warning/error.
I tried relative path, like
QFile tableFile("table"+QString::number(actualSize)+".txt");
But none of the methods I come up with was good.
You should be able to use / separators for all QFile-related paths. Open the file before you read it and close it when done.
int actualSize = 8;
QFile tableFile("C:/Users/Ms/Documents/L3/table"+QString::number(actualSize)+".txt");
if(tableFile.exists() && tableFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream in(&tableFile);
QString oneLine;
oneLine.append(in.readAll());
messageLabel->setText(oneLine);
tableFile.close();
} else
{
messageLabel->setText("Not open");
}

Reading from Multiple long .txt files in Qt

I am trying to read data from Multiple files in Qt.
This how I am doing it:
void MainWindow::on_pushButton_3_clicked()
{
QString path = "C:/MyDevelopment/readfiles";
QDir dir(path);
QStringList filters;
filters << "*.txt";
foreach ( QString fileName, dir.entryList(filters, QDir::Files) )
{
QFile readFile(fileName);
if(!readFile.open(QIODevice::ReadOnly | QIODevice::Text ) )
{
qDebug("Failed to read file.....");
//return ;
}
QTextStream in(&fileName);
while (!in.atEnd())
{
QString line = in.readLine();
qDebug() << line;
}
}
it is always going in failed to open. what i am doing wrong here??
in mentioned directory all files are .txt files.

Saving a qlistwidget after closing application

I have a program that allows for a user to create a profile that saves values using qsettings, the user accesses their profile by clicking on the name in a qlistwidget. I am trying to save the names of the profiles by using a text file but I am having trouble saving more than one profile name at a time. thank you! here is the code:
for saving a profilename to the text document
void Profile::writeProfilenames()
{
QString profilename = ui->lineEdit_profilename->text();
profilename = profilename.simplified();
QFile pfile("profilenames.txt");
if (!pfile.open(QFile::WriteOnly | QIODevice::Text))
{
return;
}
QTextStream out(&pfile);
out << profilename;
pfile.flush();
pfile.close();
}
for retrieving the profile names from the document
void Profile::readProfilenames()
{
QFile pfile("profilenames.txt");
if (!pfile.open(QIODevice::ReadOnly |
QIODevice::Text))
{
return;
}
QString proname = pfile.readLine();
QListWidgetItem *itm = new QListWidgetItem;
itm->setText(proname);
ui->listWidget_profiles->insertItem(0,itm);
}
P.S. if you know of a better way to do this then feel free to share! (with example please)
I don't quite see why you're saving the list of names in a text file, while the settings themselves are saved in a platform-specific fashion using QSettings.
The code you show has several problems:
Presumably you don't want to "write" the name to the file, overwriting the existing contents at the beginning, but specifically to append to the file. You also must specify a writable path to the file, so far you're using the current working directory that is: variable, not under your control, and not necessarily writable. Your code also doesn't handle repeated names.
QFile is a proper C++ class, and embodies the RAII principles. You don't have to do anything to flush and close the file. The compiler takes care of generating the proper code for you. That's why you're using C++ and not C, after all. Yes, your code compiles, but it reads like C, and such verbosity is unnecessary and counterproductive.
You're only retrieving one name from the file. You want to retrieve all of them.
I'd say that you should dispense with the file access, set up your application's identification, a crucial prerequisite to using QSettings, and, finally, use them:
struct Profile {
QString name;
int age;
}
void saveProfiles(const QList<Profile> & profiles)
{
QSettings s;
s.beginWriteArray("profiles");
for (int i = 0; i < profiles.size(); ++i) {
s.setArrayIndex(i);
const Profile & p = profiles.at(i);
s.setValue("name", p.name);
s.setValue("age", p.age);
}
s.endArray(); //optional
}
QList<Profile> loadProfiles()
{
QList<Profile> profiles;
QSettings s;
int size = s.beginReadArray("profiles");
for (int i = 0; i < size; ++i) {
s.setArrayIndex(i);
Profile p;
p.name = s.value("name").toString();
p.age = s.value("age").toInt();
profiles << p;
}
s.endArray(); // optional
return profiles;
}
int main(int argc, char ** argv) {
QApplication app(argc, argv);
app.setOrganizationName("fluxD613"); // ideally use setOrganizationDomain instead
app.setApplicationName("fluxer");
...
return app.exec();
}
After a lot more research and trial and error I came up with the following code that does the trick:
this function is implemented when I close the profiles dialog window and return to the main window using QCloseEvent.
void Profile::writeProfilenames()
{
QFile pfile("profilenames.txt");
if (!pfile.open(QFile::WriteOnly | QIODevice::Text))
{
return;
}
for(int row = 0; row < ui->listWidget_profiles->count(); row++)
{
QListWidgetItem *item = ui->listWidget_profiles->item(row);
QTextStream out(&pfile);
out << item->text().simplified() << "\n";
}
pfile.close();
}
reading the list of profilenames is implemented when I open the dialog window just under ui->setup(this).
void Profile::readProfilenames()
{
QFile pfile("profilenames.txt");
if (!pfile.open(QIODevice::ReadOnly |
QIODevice::Text))
{
return;
}
QTextStream in(&pfile);
while (!in.atEnd())
{
QString line = in.readLine();
QListWidgetItem *item = new QListWidgetItem;
item->setText(line);
ui->listWidget_profiles->addItem(item);
}
pfile.close();
}
I am now working on making sure the user does not enter a profilename that already exists and deleting a profilename from the QListWidget.

printing lines from multiple files

Im trying to print the first line from each file, then the second line from each file and so on.
When getline = EOF, then that file is closed and filesAreOpen is decremented, though the program loops forever
void PrintLines(ifstream files[], size_t count)
{
string s;
ifstream *end, *start;
int filesAreOpen = count;
//continue while filesAreOpen > 0
while(filesAreOpen)
{
}
}
Actually you don't have to close files if EOF is reached. That will make your code much slower and painful to manage. Because you have to check if it is open, which involves file names. In this case, files are already open and you will read first line from each file than second line from each file and so on. But if a file reaches EOF, then of course you will miss that file and continue to read lines from other files. Until all files are reached EOF. Then close them all.
void PrintLines(ifstream files[], size_t count)
{
int filesAreOpen = count;
char line[250];
//continue while filesAreOpen > 0
while(filesAreOpen)
{
for(int i=0; i<count; i++)
{
if (!infile[i].eof())
{
infile[i].getline(line,250);
cout << line;
}
else
filesAreOpen--;
}
}
for(int i=0; i<count; i++)
files[i].close();
}

Populating Table Widget from Text File in Qt

I'm new to Qt and need some help with the following:
I would like to create a GUI containing a Table Widget that is populated by information coming from a tab delimited text file. In my GUI, the user would first browse for the text file and then it would then show the contents in the Table Widget. I've done the browse part, but how do I load the data from the text file into the Table Widget?
It's two steps, parse the file, and then push it into the widget.
I grabbed these lines from the QFile documentation.
QFile file("in.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
while (!file.atEnd()) {
QByteArray line = file.readLine();
process_line(line);
}
Your process_line function should look like this:
static int row = 0;
QStringList ss = line.split('\t');
if(ui->tableWidget->rowCount() < row + 1)
ui->tableWidget->setRowCount(row + 1);
if(ui->tableWidget->columnCount() < ss.size())
ui->tableWidget->setColumnCount( ss.size() );
for( int column = 0; column < ss.size(); column++)
{
QTableWidgetItem *newItem = new QTableWidgetItem( ss.at(column) );
ui->tableWidget->setItem(row, column, newItem);
}
row++;
For more information about manipulating QTableWidgets, check the documentation. For new users using the GUI builder in Qt Creator, it is tricky figuring it out at first.
Eventually I would recommend to switching to building the GUI the way they do in all their examples... by adding everything by hand in the code instead of dragging and dropping.
Sorry...
void squidlogreader_::process_line(QString line)
{
static int row = 0;
QStringList ss = line.split('\t');
if(ui->tableWidget->rowCount() < row + 1)
ui->tableWidget->setRowCount(row + 1);
if(ui->tableWidget->columnCount() < ss.size())
ui->tableWidget->setColumnCount( ss.size() );
for( int column = 0; column < ss.size(); column++)
{
QTableWidgetItem *newItem = new QTableWidgetItem( ss.at(column) );
ui->tableWidget->setItem(row, column, newItem);
}
row++;
}
void squidlogreader_::on_pushButton_clicked()
{
QFile file("in.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
while (!file.atEnd()) {
QString line = file.readLine();
process_line(line);
}

Resources