5、按行读取文件中的内容,并输出长度最大的行

来源:互联网 发布:抓取数据的免费软件 编辑:程序博客网 时间:2024/05/17 07:19

从test.txt中按行读取内容,然后比较输出最大长度的行。思路很简单,直接读程序即可,测试输出是可用的。

#include <stdio.h>#include <string.h> #define MAXLEN 100int main(int argc, char* argv[]){FILE* fp;char MaxBuf[MAXLEN];char buf[MAXLEN];int maxlenth=0, templenth=0;char c;fp = fopen("test.txt", "r");while((templenth=getlines(fp, buf, MAXLEN)) > 0){if(templenth > maxlenth){maxlenth = templenth;copy(MaxBuf, buf, maxlenth+1);}printf("%s", buf);}printf("MAXLEN:%d\t%s", maxlenth, MaxBuf);}int getlines(FILE* fp, char* buffer, int maxlen){int nl=0;char c=0;while(((c=getc(fp)) != EOF) && (c != '\n') && (nl<maxlen-1)){buffer[nl++] = c;}if(c == '\n')buffer[nl++] = c;buffer[nl] = '\0';return nl;}int copy(char to[], char from[], int lenth){int i;for(i=0;i<lenth; i++)to[i] = from[i];}