最近在複習C語言 看到linux下head 和cat 的命令很好使 嘗試本身實現了一下
因此就弄了兩個程序 一個是讀取指定行數 一個是 讀取幾行;
系統環境 ubuntu 9.10
編程環境 GCC 4.41
截圖以下:
代碼以下
/*程序功能 實現指定文本的行數讀取
*使用方法 a.out <filename> <line no>
*/

#include <stdio.h>

#include <stdlib.h>

#include <
string.h>
char *read_line(
const
char *pathname,
int line_n)

{
int len,file_size;
char *str,*buf,*p;

FILE *fp;

fp=fopen(pathname,
"r" );
if(fp==NULL){

perror(
"fopen error");

exit(1);

}

fseek(fp,0,SEEK_END);

file_size=ftell(fp);

str=(
char *)calloc(file_size,
sizeof(
char));

rewind(fp);

fread(str,
sizeof(
char),file_size,fp);

str[file_size]='\0';

p=str;
char *q;
int n=line_n-1;

q=str;
while(*p++){
if(*p=='\n')

line_n--;
if(line_n==0)
break;

}
while(*q++)

{
if(*q=='\n')

n--;
if(n==0)
break;

}

q++;
if(*p=='\0')

{

printf(
"已經到行尾\n");

exit(1);

}

len=p-str;

str[len]='\0';

buf=q;

free(str);

fclose(fp);
return buf;

}
int main(
int argc,
char** argv)

{
int i=atoi(argv[2]);
char *buf;

buf= read_line(argv[1],i);

printf(
"%s\n",buf);
return 0;

}