c语言编程 从文件中读入多行字符串,并在另一文件中输出最长的一行,若有多行最长,则输出第一行

如题所述

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
 FILE *fp;
 char filename[20],s[100],t[100];
 gets(filename);//读文件名 注意路径如f:\1.txt
 if((fp=fopen(filename,"r"))==NULL)
  {printf("Can not open file.\n");exit(0);}
 fgets(s,100,fp);//读字符串
 while(!feof(fp))
 {
  fgets(t,100,fp);
  if(strlen(t)>strlen(s)) strcpy(s,t);//最长字符串复制给s,相同长度不复制
 }
 fclose(fp);
 gets(filename);//写文件名
 if((fp=fopen(filename,"w"))==NULL)
  {printf("Can not open file.\n");exit(0);}
 fputs(s,fp);//写字符串
 fclose(fp);
}



温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-12-22

// duxiefile.cpp : Defines the entry point for the console application.

//


#include "stdafx.h"

#include "stdlib.h"

#include "stdio.h"

#include "string.h"


int _tmain(int argc, _TCHAR* argv[])

{

FILE *fp;

if((fp=fopen("d:\\test.txt","r"))==NULL)

{

printf("can't open this file\n");

system("pause");

exit(0);

}

char *string;

char *maxstr;

char strarray[20];

char maxarray[20];


string=strarray;

maxstr=maxarray;


int strlong=0;

int maxlong=0;


while(!feof(fp))

{

fgets(string,20,fp);

strlong=strlen(string)-1;


if(strlong>maxlong)

{

strcpy(maxstr,string);

maxlong=strlong;

}

}


fclose(fp);


printf("%d",maxlong);

printf("%s",maxstr);


FILE *fp2=fopen("d:\\testo.txt","w");

fputs(maxstr,fp2);

fclose(fp2);


system("pause");

}

相似回答