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

程序如下:

#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. C语言处理HTML
  3. PHP和C语言共享内存通信以及信号量互斥
  4. Linux下Socket通信、共享内存和信号量混合使用的例子
  5. Linux共享内存进程间通信