如何计算输入文件的行数

How to count the number of lines of an input file?

本文关键字:文件 输入 何计算 计算      更新时间:2023-10-16

我知道输入文件的每一行都包含五个数字,我希望我的c++程序在不询问用户的情况下自动确定文件中有多少行。有没有一种方法可以在不使用getline或字符串类的情况下做到这一点?

这就是我要做的…

#include <iostream> 
#include <fstream>
using namespace std;
int main()
{
    string fileName = "Data.txt";
    std::ifstream f(fileName, std::ifstream::ate | std::ifstream::binary);
    int fileSize = f.tellg() / 5 * sizeof(int);
    return 0;
}

该代码假定一个名为Data.txt的文件,并且每行上的5个数字都是int类型,并且没有用空格或分隔符分隔。请记住,在文本文件的情况下,每一行都将终止于一个换行符,因此这种不考虑它们的技术会产生误导性的结果。

当然,您所要做的只是简单地读取文件,同时检查转义序列。请注意,n转义序列在写入时被转换为系统特定的换行转义序列,在文本模式下读取时反之亦然

一般来说,这个代码片段可能会对您有所帮助。

给定文件somefile.txt

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

编译下面的代码并输入文件名somefile.txt

#include <iostream>
#include <fstream>
inline size_t newlineCount (std::istream& stream)
{
    size_t linesCount = 0;
    while (true)
    {
        int extracted = stream.get();
        if (stream.eof()) return linesCount;
        else if (extracted == 'n') ++linesCount;
    }
}
int main(int argc, char* argv[])
{
    std::string filename;
    std::cout << "File: ";
    std::cin >> filename;
    std::ifstream fileStream;
    fileStream.exceptions(fileStream.goodbit);
    fileStream.open(filename.c_str(), std::ifstream::in);
    if (!fileStream.good())
    {
        std::cerr << "Error opening file "" << filename << "". Aborting." << std::endl;
        exit(-1);
    }
    std::cout << "Lines in file: " << newlineCount(fileStream) << std::endl;
    fileStream.close();
}

给出输出

File: somefile.txt
Lines in file: 4