最近在複習C語言 忽然想寫些什麼東西了,就實現了一下 head命令 在這個小程序的編寫過程當中 仍是遇到了不少問題,使我瞭解了 指針的使用.
編程環境 Ubuntu 9.10 gcc 4.41
調用方式 a.out <filename> <lineno>
源碼以下

#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;
while(*p++){
if(*p=='\n')

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

}

len=p-str;

str[len]='\0';

buf=str;

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;

}