在txt文件中获取行数时出现问题 [英] Problem getting number of lines in txt file

查看:132
本文介绍了在txt文件中获取行数时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!
我是C语言的新手,无法编写函数来计算文本文件中的行数.我现在拥有的代码进入了一个无限循环,我必须打破它,并且在调试器(日食)中看起来好像我的行计数器从未增加过.以下是相关代码:

Hello Everyone!
I am a novice c programmer and I am having trouble writing a function to count the number of lines in a text file. The code I have now just goes into an infinite loop and I have to break out of it, and in the debugger (eclipse) it doesn''t look like my line counter is ever incremented. Here is the relevant code:

int numOfLines(FILE*); //Function declaration
int main()
{
     FILE* stats;
     int lines;
     char buffer[BUFSIZ+1];

     stats = fopen("TestStats.txt", "r+"); //opening text document
     lines = numOfLines(stats); // function call
     printf("%d", lines);
     gets(buffer); //I just use this to end a program, I''ve heard it is unhealty, any suggestions?
     fclose(stats);
     return 0;

}

int numOfLines(FILE* stats) //function definition
{
     int lines = 1;
     char character[1] = "1";

     while (character[0] != EOF)
     {
          fgets(character, 1, stats); //get 1 char from stats
          if (character[0] == ''\n'')  //if it is a \n then add one to lines
               lines = lines + 1; 
     }
     
     return lines; 
}



这只是整个程序的一部分,我必须在内存中键入此内容,因为我在另一台计算机上.另外,打开文件并计算其中的行数是否会影响写游标的位置?也就是说,如果我返回并重新打开"TestStats.txt"以向其添加数据或向其中写入数据,我是否必须对fseek进行一些幻想才能在文件的末尾或开头进行写操作?最后一个问题是,如果您使用fseek并向文件中写入内容,它会覆盖那里的内容,还是将其插入(如果写入,是否有一种简单的插入方法)?

非常感谢您的帮助,谢谢您的宝贵时间!

*编辑,这也算空行吗? (我需要它)



This is only part of the whole program, I had to type this out of memory because I am on a different machine. Also, does opening a file and counting the lines in it affect where the write cursor is? That is, if I go back and re-open ''TestStats.txt'' to append or write data to it, am I going to have to do something fancy with fseek to write at the end or beginning of the file? And one last question, if you use fseek and write something to file, does it write over what was there, or does it insert (and if it writes over, is there an easy way to insert)?

I would greatly appreciate any help, thank you for your time!

*Edit, also will this count blank lines? (I need it to)

推荐答案

您没有正确读取行.例如,这是正确的: http://answers.yahoo.com/question/index?qid=20070724065318AAOd1mP [^ ].

请注意一个限制:您需要使用足够大的缓冲区来容纳一行.该代码基于以下假设:该行的长度不超过缓冲区大小(80-1).

—SA
You''re not reading lines correctly. For example, this is correct: http://answers.yahoo.com/question/index?qid=20070724065318AAOd1mP[^].

Pay attention for one limitation: you need to use a buffer which is big enough to hold a line. The code is based on assumption that the line in not longer than a buffer size (80-1).

—SA


这篇关于在txt文件中获取行数时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆