如何计算输入文件的行数
How to count the number of lines of an input file?
我知道输入文件的每一行都包含五个数字,我希望我的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
相关文章:
- C++文本文件输入
- C++ 中文件输入输出中的长长 v/s int
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 用空格填充 2D 数组(从文件输入)
- 流对象来表示文件输入,然后是标准输入?
- 用精神解析文件输入
- 从文件输入和输出
- 来自文本文件输入 c++ 的向量
- 如何通过键盘或分数文件输入分数
- 了解文件输入和输出,我可以写入文件,但无法从文件打印
- 词频程序 - 文件输入太大?
- 尝试从 csv 文件输入大量数据时出错
- 如何将文件从文件输入到C 中的矩阵中
- 如何从Windows CMD运行可执行文件并将其传递给文件输入的参数参数和重定向
- 如何解析文本文件并使用构造函数中的文件输入来创建对象的容器
- 这是读取文件输入的正确方法吗?
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- 如何创建一个具有空值、递减编号系统和.txt文件输入值的二维阵列网格
- C 文件输入流循环问题
- 使用对输入整数的文件输入