统计文件中的行数

来源:百度知道 编辑:UC知道 时间:2024/06/09 10:52:45
编写一个程序,它读入一个文件,并统计文件中的行数。
是用C++中的 I/O流做的。
急需 14号中午之前要程序。 希望越详细越好。
这个程序应该说很容易的。
要是能有注释就更好了 现在就是有个问题就是 不明白 程序打开的文件在哪里 路径要怎么设置?
我机器的VC出毛病了 具体就得明天检验下哪个能用了

#include <iostream>
#include <fstream>
using namespace std;

double analyze( const char* t )
{
ifstream ifs(t);
if(ifs.fail())
{
cerr<<"打开失败!"<<endl;
return -1;
}
double num = 0;
char buffer;
while( !ifs.eof() )
{
buffer = ifs.get();
if( buffer == '\n' )
num++;
}

ifs.close();

return num;
}

int main(void)
{
cout<<"main.cpp is"<<analyze("main.cpp")<<endl;

return 0;
}

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
string fname;//用来保存文件名,如果在命令行用test filename执行,fname为filename,如果直接启动,fname默认为test.txt
string strdata;//只是用来保存一行,在这里没实际作用.
int line_count = 0;//行