输出文本中最长的一行

2009-04-01 20:01 / no comment / 52 views /

用户输入一个文本名,编程实现输出文本中最长的一行。如果最长的不止一行,请全部输出。

程序如下:

#include<stdio.h>
int main(int a, char * arg[])
{
 char file_name[31];
 FILE * file;
 long lines[20];   /* store the offset  */
 unsigned int length = 0; /*  length of the line */
 unsigned int num = 0;  /*  number of lines */
 char buf[200];
 char c;
 unsigned int n = 0;

 /* Get the file name, and print the name to the screen. */
 if( a == 2 ){
  strcpy(file_name,arg[1]);
 }
 else{
  printf(“\nPlease enter a file name:”);
  scanf(“%s”,file_name);
 }
 printf(“The file name is: %s\n”,file_name);

 /* Open the file, the program will be stop if it failed. */
 file = fopen(file_name,”r”);
 if( file==NULL ){
  printf(“No such file!\n”);
  return 0;
 }

 /* Fined out the lengthest line. */
 do{
 c = fgetc( file );
 n++;
 if( c==’\n’ ){
  if( n>length ){
   lines[0] = ftell(file)-n-1;
   num = 1;
   length = n;
  }
  else if( n==length ){
   lines[num] = ftell(file)-n-1;
   num++;
  }
  else ;
  n = 0;
 }
 }while(c!=EOF);
 n = n;

 /* Print. */
 printf(“The longest lines of the file is:\n”);
 while( 0 != num– ){
 fseek( file,lines[num],SEEK_SET );
 fgets( buf,length,file );
 printf(“%s\n”,buf );
 }
}

BUG肯定有,主要就是缓冲区溢出。分数应该会得。该程序可以用命令行方式输入文件名参数。

Related Posts

  1. 统计代码行数
  2. 线性表
  3. C语言HTML解析器
  4. vim命令速查表
  5. 删除一个字符串中的空格
  6. PHP和C语言共享内存通信以及信号量互斥
  7. Linux下Socket通信、共享内存和信号量混合使用的例子
  8. 用shell脚本逐行读取文件
  9. Linux下用户态直接读写磁盘扇区
  10. C语言与PHP与JavaScript通信

Tags: .

Get a Trackback link

No Comments Yet

You can be the first to comment!

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>