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)]);
相关推荐
LCS-31214 分钟前
Python爬虫实战: 爬虫常用到的技术及方案详解
开发语言·爬虫·python
枫の准大一14 分钟前
【C++游记】List的使用和模拟实现
开发语言·c++·list
穷儒公羊15 分钟前
第二章 设计模式故事会之策略模式:魔王城里的勇者传说
python·程序人生·设计模式·面试·跳槽·策略模式·设计规范
qq_4335545422 分钟前
C++深度优先搜素
开发语言·c++·深度优先
心本无晴.27 分钟前
面向过程与面向对象
python
花妖大人28 分钟前
Python用法记录
python·sqlite
站大爷IP35 分钟前
用PyQt快速搭建桌面应用:从零到实战的实用指南
python
站大爷IP1 小时前
PyCharm:Python开发者的智慧工作台全解析
python
zhanghongyi_cpp1 小时前
linux的conda配置与应用阶段的简单指令备注
linux·python·conda
MThinker1 小时前
14.examples\01-Micropython-Basics\demo_yield.py 加强版
python·学习·智能硬件·micropython·canmv·k230