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)]);
相关推荐
第七序章31 分钟前
【C++STL】list的详细用法和底层实现
c语言·c++·自然语言处理·list
逆小舟2 小时前
【Linux】人事档案——用户及组管理
linux·c++
l1t2 小时前
利用DeepSeek实现服务器客户端模式的DuckDB原型
服务器·c语言·数据库·人工智能·postgresql·协议·duckdb
l1t4 小时前
利用美团龙猫用libxml2编写XML转CSV文件C程序
xml·c语言·libxml2·解析器
lqjun08275 小时前
Qt程序单独运行报错问题
开发语言·qt
酷飞飞6 小时前
Python网络与多任务编程:TCP/UDP实战指南
网络·python·tcp/ip
风中的微尘7 小时前
39.网络流入门
开发语言·网络·c++·算法
数字化顾问7 小时前
Python:OpenCV 教程——从传统视觉到深度学习:YOLOv8 与 OpenCV DNN 模块协同实现工业缺陷检测
python
混分巨兽龙某某8 小时前
基于Qt Creator的Serial Port串口调试助手项目(代码开源)
c++·qt creator·串口助手·serial port
小冯记录编程8 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio