C++/QT/Python/MATLAB获取文件行数的示例详解

2024-03-01 0 134
目录
  • 1. C获取文件行数
  • 2. C++获取文件行数
  • 3. Qt获取文件行数
  • 4. Python获取文件行数
  • 5. 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获取文件行数的示例详解的文章就介绍到这了,更多相关获取文件行数内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!

您可能感兴趣的文章:

  • php 获取文件行数的方法总结
  • PHP获取文件行数的方法
  • java工具类之实现java获取文件行数
  • python统计指定目录内文件的代码行数
  • python计算文本文件行数的方法
  • C语言实现的统计php代码行数功能源码(支持文件夹、多目录)

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 编程综合 C++/QT/Python/MATLAB获取文件行数的示例详解 https://www.u-9.cn/biancheng/bczonghe/181253.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务