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)]);
相关推荐
江沉晚呤时4 小时前
在 C# 中调用 Python 脚本:实现跨语言功能集成
python·microsoft·c#·.net·.netcore·.net core
m0_535064605 小时前
C++模版编程:类模版与继承
java·jvm·c++
电脑能手5 小时前
如何远程访问在WSL运行的Jupyter Notebook
ide·python·jupyter
Edward-tan5 小时前
CCPD 车牌数据集提取标注,并转为标准 YOLO 格式
python
老胖闲聊6 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
倔强青铜三6 小时前
苦练Python第18天:Python异常处理锦囊
人工智能·python·面试
Tanecious.6 小时前
C++--红黑树封装实现set和map
网络·c++
倔强青铜三6 小时前
苦练Python第17天:你必须掌握的Python内置函数
人工智能·python·面试
迷路爸爸1806 小时前
让 VSCode 调试器像 PyCharm 一样显示 Tensor Shape、变量形状、变量长度、维度信息
ide·vscode·python·pycharm·debug·调试
咸鱼鲸7 小时前
【PyTorch】PyTorch中的数据预处理操作
人工智能·pytorch·python