读取文件的特定的几行

C实现:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
void main()
{
 char* poem="\n program is fun\n when the work is down\n if  you wanna make your work also fun:\nuse c++!";
 FILE* fp=fopen("zhj.txt","w");
 fprintf(fp,"%s",poem);
 fclose(fp);

 char *str=(char*)malloc(256*sizeof(char));
 char* ch=(char*)malloc(256*sizeof(char));
 memset(str,'\0',256*sizeof(char));
 memset(ch,'\0',256*sizeof(char));
 int count=0;
 printf("start\n");
 FILE* fp1;
 fp1=fopen("zhj.txt","r");
 while(!feof(fp1))
 {
    fgets(str,256,fp1);
    //fscanf(fp1,"%s",&str);
    printf("%s\n",str);
    count=count+1;
    if(count>1&&count<5)
    strcat(ch,str);
    //fseek(fp1,1L,SEEK_CUR);
 }
 printf("end read,\nch=%s\n",ch);
 fclose(fp1);
 printf("end\n");
 FILE* fp2=fopen("res.txt","w");
 fprintf(fp2,"%s",ch);
 fclose(fp2);

 if(str) free(str);
 if(ch) free(ch);
}

Python实现:

import sys
import string
poem='''\
Program is fun
when the work is done
if you wanna make your work also fun:
use python!
'''

f=file('poem.txt','w')
f.write(poem)
f.close()

f=file('poem.txt')

count=1
str1=' '
while True:
       line = f.readline()
       if len(line)==0:
        break
       elif count>1 and count<4:
           str1 += line
       count=count+1
       print line
f.close()

f1=file('res.txt','w')
f1.write(str1)
f1.close()






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值