用c语言怎么读取txt文件中的行数

时间:2024-01-03 18:10:41 买帖  | 投诉/举报

篇首语:本文由小编为大家整理,主要介绍了用c语言怎么读取txt文件中的行数相关的知识,希望对你有一定的参考价值。

读取文件行数, 可以逐个字符读取文件,到文件尾,统计\\n的个数

参考代码如下

#include <stdio.h>
int main()

    int c;
    FILE *fp;
    int lines=0;
    fp=fopen("in.txt", "rb");
    if(fp)
    
        while((c=fgetc(fp)) != EOF)
            if(c==\"\\n\") lines++;
        printf("%d\\n",lines);
        fclose(fp);
    
    return 0;

也可以通过fgets函数,每次读取一行,到文件尾,然后计算读取的次数

#include <stdio.h>
#include <string.h>
int main()

    char s[100];
    FILE *fp;
    int lines=0;
    fp=fopen("in.txt", "r");
    if(fp)
    
        while((fgets(s,100,fp)) != NULL)
            if(s[strlen(s)-1]==\"\\n\") lines++;
        printf("%d\\n",lines);
        fclose(fp);
    
    return 0;
参考技术A 简单办法是:打开文件,用fgetc读取字符并判断是否为'\n',是则给初值为0的行记数变量增1。

Qt中怎样读取文件指定的行?

你提到行,很明显你要操作的是文本文件,文本文件是顺序文件,只能用
QFile file("FileName");
QTextStream in(&file);
int i=0;
QString line="";
while (!in.atEnd() && ++i<=lineNo )
line=in.readLine();

其它用途请用随机存储!
参考技术A 1、qint64 QFile::readLineData ( char * data, qint64 maxlen )
[virtual protected]
Reimplemented from QIODevice::readLineData().

2、qint64 QIODevice::readLine ( char * data, qint64 maxSize )
This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data, and returns the number of bytes read. If a line could not be read but no error ocurred, this function returns 0. If an error occurs, this function returns the length of what could be read, or -1 if nothing was read.
A terminating '\0' byte is always appended to data, so maxSize must be larger than 1.
Data is read until either of the following conditions are met:
The first '\n' character is read.
maxSize - 1 bytes are read.
The end of the device data is detected.
For example, the following code reads a line of characters from a file:
QFile file("box.txt");
if (file.open(QFile::ReadOnly))
char buf[1024];
qint64 lineLength = file.readLine(buf, sizeof(buf));
if (lineLength != -1)
// the line is available in buf



3、QByteArray QIODevice::readLine ( qint64 maxSize = 0 )
This is an overloaded function.
Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray.
This function has no way of reporting errors; returning an empty QByteArray() can mean either that no data was currently available for reading, or that an error occurred.
参考技术B QFile file(srcDir);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))

int row=0;
while (!file.atEnd())

QByteArray line = file.readLine();
if(++row==2)
//QString a=file.readLine();
QString str(line);
qDebug() << str;


file.close();

以上是关于用c语言怎么读取txt文件中的行数的主要内容,如果未能解决你的问题,请参考以下文章