C++/QT/Python/MATLAB获取文件行数的示例详解
更新时间:2023年08月11日 08:38:16 作者:罗伯特祥
这篇文章主要为大家学习介绍了如何利用C++、QT、Python、MATLAB分别实现获取文件行数的功能,文中的示例代码讲解详细,需要的可以参考一下
1. C获取文件行数
#include <stdio.h>
int main() {
FILE *file = fopen("path/to/your/file.txt", "r");
if (file == NULL) {
printf("Failed to open the file!\n");
return 0;
}
int lineCount = 0;
char ch;
while ((ch = fgetc(file)) != EOF) {
if (ch == '\n') {
lineCount++;
}
}
printf("Line count: %d\n", lineCount);
fclose(file);
return 0;
}2. C++获取文件行数
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("path/to/your/file.txt");
if (!file) {
std::cout << "Failed to open the file!" << std::endl;
return 0;
}
int lineCount = 0;
std::string line;
while (std::getline(file, line)) {
lineCount++;
}
std::cout << "Line count: " << lineCount << std::endl;
file.close();
return 0;
}3. Qt获取文件行数
#include <QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("path/to/your/file.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Failed to open the file!";
return a.exec();
}
QTextStream in(&file);
int lineCount = 0;
while (!in.atEnd())
{
QString line = in.readLine();
lineCount++;
}
qDebug() << "Line count: " << lineCount;
file.close();
return a.exec();
}4. Python获取文件行数
file_path = 'path/to/your/file.txt'
try:
with open(file_path, 'r') as file:
line_count = sum(1 for line in file)
print(f"Line count: {line_count}")
except IOError:
print("Failed to open the file!")5. MATLAB获取文件行数
方法一:使用numel函数
filename = 'your_file.txt'; % 文件名
fileID = fopen(filename, 'r'); % 打开文件
data = textscan(fileID, '%s', 'Delimiter', '\n'); % 按行读取数据并存储在一个单元格数组中
fclose(fileID); % 关闭文件
numLines = numel(data{1}); % 计算行数
disp(['文件行数为:', num2str(numLines)]);方法二:使用size函数
filename = 'your_file.txt'; % 文件名
fileID = fopen(filename, 'r'); % 打开文件
data = textscan(fileID, '%s', 'Delimiter', '\n'); % 按行读取数据并存储在一个单元格数组中
fclose(fileID); % 关闭文件
numLines = size(data{1}, 1); % 计算行数
disp(['文件行数为:', num2str(numLines)]);到此这篇关于C++/QT/Python/MATLAB获取文件行数的示例详解的文章就介绍到这了,更多相关获取文件行数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
IntelliJ IDEA 2020最新注册码(亲测有效,可激活至 2089 年
这篇文章主要介绍了IntelliJ IDEA 2020最新注册码,亲测有效,可激活至 2089 年,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-05-05
如何在本地部署 DeepSeek Janus Pro 文生图大模型
DeepSeek JanusPro模型在本地成功部署,支持图片理解和文生图功能,通过Gradio界面进行交互,展示了其强大的多模态处理能力,本文介绍本地部署 DeepSeek Janus Pro 文生图大模型的操作,感兴趣的朋友一起看看吧2025-02-02
MyBatisCodeHelper-Pro插件破解版详细教程[2.8.2]
MyBatisCodeHelper-Pro是IDEA下的一个插件,功能类似mybatis plugin。这篇文章给大家介绍MyBatisCodeHelper-Pro插件破解版[2.8.2]的相关知识,感兴趣的朋友跟随小编一起看看吧2020-09-09


最新评论