C++/QT/Python/MATLAB獲取文件行數(shù)的示例詳解
更新時(shí)間:2023年08月11日 08:38:16 作者:羅伯特祥
這篇文章主要為大家學(xué)習(xí)介紹了如何利用C++、QT、Python、MATLAB分別實(shí)現(xiàn)獲取文件行數(shù)的功能,文中的示例代碼講解詳細(xì),需要的可以參考一下
1. C獲取文件行數(shù)
#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++獲取文件行數(shù)
#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獲取文件行數(shù)
#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獲取文件行數(shù)
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獲取文件行數(shù)
方法一:使用numel
函數(shù)
filename = 'your_file.txt'; % 文件名 fileID = fopen(filename, 'r'); % 打開文件 data = textscan(fileID, '%s', 'Delimiter', '\n'); % 按行讀取數(shù)據(jù)并存儲(chǔ)在一個(gè)單元格數(shù)組中 fclose(fileID); % 關(guān)閉文件 numLines = numel(data{1}); % 計(jì)算行數(shù) disp(['文件行數(shù)為:', num2str(numLines)]);
方法二:使用size
函數(shù)
filename = 'your_file.txt'; % 文件名 fileID = fopen(filename, 'r'); % 打開文件 data = textscan(fileID, '%s', 'Delimiter', '\n'); % 按行讀取數(shù)據(jù)并存儲(chǔ)在一個(gè)單元格數(shù)組中 fclose(fileID); % 關(guān)閉文件 numLines = size(data{1}, 1); % 計(jì)算行數(shù) disp(['文件行數(shù)為:', num2str(numLines)]);
到此這篇關(guān)于C++/QT/Python/MATLAB獲取文件行數(shù)的示例詳解的文章就介紹到這了,更多相關(guān)獲取文件行數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
git工作區(qū)暫存區(qū)與版本庫基本理解及提交流程全解
這篇文章主要為大家介紹了git工作區(qū)暫存區(qū)與版本庫基本理解及提交流程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-04-04基數(shù)排序算法的原理與實(shí)現(xiàn)詳解(Java/Go/Python/JS/C)
基數(shù)排序(RadixSort)是一種非比較型整數(shù)排序算法,其原理是將整數(shù)按位數(shù)切割成不同的數(shù)字,然后按每個(gè)位數(shù)分別比較。本文將利用Java/Go/Python/JS/C不同語言實(shí)現(xiàn)基數(shù)排序算法,感興趣的可以了解一下2023-03-03Typora+PicGo+GitHub實(shí)現(xiàn)md自帶圖床效果
這篇文章主要介紹了Typora+PicGo+GitHub實(shí)現(xiàn)md自帶圖床效果,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04