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

1. C获取文件行数

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++获取文件行数

cpp 复制代码
#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获取文件行数

cpp 复制代码
#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获取文件行数

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函数

    matlab 复制代码
    filename = 'your_file.txt';  % 文件名
    fileID = fopen(filename, 'r');  % 打开文件
    data = textscan(fileID, '%s', 'Delimiter', '\n');  % 按行读取数据并存储在一个单元格数组中
    fclose(fileID);  % 关闭文件
    
    numLines = numel(data{1});  % 计算行数
    disp(['文件行数为:', num2str(numLines)]);
  • 方法二:使用size函数

    matlab 复制代码
    filename = 'your_file.txt';  % 文件名
    fileID = fopen(filename, 'r');  % 打开文件
    data = textscan(fileID, '%s', 'Delimiter', '\n');  % 按行读取数据并存储在一个单元格数组中
    fclose(fileID);  % 关闭文件
    
    numLines = size(data{1}, 1);  % 计算行数
    disp(['文件行数为:', num2str(numLines)]);
相关推荐
databook5 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar6 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户8356290780517 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_7 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
感哥7 小时前
C++ 面向对象
c++
沐怡旸8 小时前
【底层机制】std::shared_ptr解决的痛点?是什么?如何实现?如何正确用?
c++·面试
数据智能老司机13 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机14 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机14 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机14 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构