我需要知道如何在不使用strlen或fstream库的情况下读取文本文件并从中找到最长行的长度。基本上,我需要使用标准输入和输出来模拟wc -L命令。我当时在考虑使用链表来存储每行的长度,然后比较每个节点,最后打印出最长的行的长度,但是我不完全确定这将如何工作以及是否会工作。
尝试这样的事情:
#include <stdio.h>
int main( int argc, char **argv)
{
FILE *in = fopen( "file.txt" );
if( in == NULL ) {
printf( "File does not exist" );
exit(-1);
}
int ch;
int current = 0;
int longest_so_far = 0;
while( (ch = fgetc(in)) != EOF ) {
if( ch == 0x0a ) { // LF, that's line end
if( current > longest_so_far ) {
longest_so_far = current;
current = 0;
}
} else {
current ++;
}
}
printf( "Longest line length: %d", longest_so_far);
}