c语言中读取磁盘文件时怎么读取下一行的文本

c语言中读取磁盘文件时怎么读取下一行的文本,第1张

char *fgets( char *string, int n, FILE *stream )

这是MSDN上说明

The fgets function reads a string from the input stream argument and stores it in string. fgets reads characters from the current stream position to and including the first newline character, to the end of the stream, or until the number of characters read is equal to n – 1, whichever comes first. The result stored in string is appended with a null character. The newline character, if read, is included in the string.

方法一: oledbconnection conn="连接字符串"string sql="select * from B1 where name='"+i+"'"OleDbDataAdapter adapter=new OleDbDataAdapter(sql,conn)DataSet ds=new DataSet()adapter.fill(ds,"B1")string a=ds.table[0].row[0]["id"].Tostring().Trim()string b=ds.table[0].row[0]["phone"].Tostring.Trim()string c=ds.table[0].row[0]["age"].Tostring.Trim()()另外也可以是方法二: oledbconnection conn="连接字符串"string sql="select * from B1 where name='"+i+"'"OleDbCommend commend=new OleDbCommend (sql,conn)OleDbDataReader reader = commend.ExecuteReader()if (reader.Read()) { string a= reader.GetString(0).Trim()string b=reader.GetString(1).Trim()string c=reader.GetString(2).Trim()}

求采纳

很遗憾,事实上计算机是不可能做到读取txt文件的第n行的时间复杂度为O(1)的。

因为txt文件是“顺序存储”,如图参考自《数据结构》

要读取第n行,必须找到第n-1行 =>则必须找到n-2行 … 必须找到第1行。所以读取第5000行的字符串,只能一行一行找,就好比人类看书,要看到第5000段( txt的第5000行 其实打印出来是第5000段)必须一段一段数,不然只能估计,就不准确了。

如果要以O(1)时间复杂度定位到第N“行”或第N个记录,必须用“索引存储”、“散列存储”等,如数据库文件会用这类存储。具体细节可以学《数据结构》、《数据库原理》等。

参考代码:

#include <stdio.h> 

//读取filename文件(路径)、第 whichLine+1 行文本。

char * ReadSpeacialLine(char *filename, int whichLine)

{

FILE *fp       

int currentLine = 0 //当前读取的行

char strLine[1024] //每行最大读取的字符数,可根据实际情况扩大

if ((fp = fopen(filename, "r")) == NULL) //判断文件是否存在及可读

{

printf("error!")

return NULL

}

while (!feof(fp))

{

if (currentLine == whichLine)

{

fgets(strLine, 1024, fp)  //读取一行

//printf("%s", strLine) //输出

return strLine

}

fgets(strLine, 1024, fp)  //读取一行,并定位到下一行

currentLine++

}

fclose(fp)                     //关闭文件

return NULL

}

int main() {

//注意 源代码里字符串写"\\",编译之后只是1个\,因为\是转义符号

char txtFile[] = "E:\\新建文本文档.txt"

int i = 11

printf("第%d行\n%s", i+1

, ReadSpeacialLine(txtFile, i)) //ReadSpeacialLine返回的字符串里自带换行

getchar() //防止结束闪退

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/10029356.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-04
下一篇 2023-05-04

发表评论

登录后才能评论

评论列表(0条)

保存