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

1. C获取文件行数

#include 

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

#include 
#include 
#include 

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

#include 
#include 
#include 
#include 

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

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!")

你可能感兴趣的:(#,▶,C/C++,#,▶,Qt,#,▶,Python,c语言,c++,qt,python)