最近在複習C語言 忽然想寫些什麼東西了,就實現了一下 head命令 在這個小程序的編寫過程當中 仍是遇到了不少問題,使我瞭解了 指針的使用.
編程環境 Ubuntu 9.10 gcc 4.41
調用方式 a.out <filename> <lineno>
源碼以下
![](http://static.javashuo.com/static/loading.gif)
#include <stdio.h>
![](http://static.javashuo.com/static/loading.gif)
#include <stdlib.h>
![](http://static.javashuo.com/static/loading.gif)
#include <
string.h>
char *read_line(
const
char *pathname,
int line_n)
![](http://static.javashuo.com/static/loading.gif)
{
int len,file_size;
char *str,*buf,*p;
![](http://static.javashuo.com/static/loading.gif)
FILE *fp;
![](http://static.javashuo.com/static/loading.gif)
fp=fopen(pathname,
"r" );
if(fp==NULL){
![](http://static.javashuo.com/static/loading.gif)
perror(
"fopen error");
![](http://static.javashuo.com/static/loading.gif)
exit(1);
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
fseek(fp,0,SEEK_END);
![](http://static.javashuo.com/static/loading.gif)
file_size=ftell(fp);
![](http://static.javashuo.com/static/loading.gif)
str=(
char *)calloc(file_size,
sizeof(
char));
![](http://static.javashuo.com/static/loading.gif)
rewind(fp);
![](http://static.javashuo.com/static/loading.gif)
fread(str,
sizeof(
char),file_size,fp);
![](http://static.javashuo.com/static/loading.gif)
str[file_size]='\0';
![](http://static.javashuo.com/static/loading.gif)
p=str;
while(*p++){
if(*p=='\n')
![](http://static.javashuo.com/static/loading.gif)
line_n--;
if(line_n==0)
break;
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
len=p-str;
![](http://static.javashuo.com/static/loading.gif)
str[len]='\0';
![](http://static.javashuo.com/static/loading.gif)
buf=str;
![](http://static.javashuo.com/static/loading.gif)
free(str);
![](http://static.javashuo.com/static/loading.gif)
fclose(fp);
return buf;
![](http://static.javashuo.com/static/loading.gif)
}
int main(
int argc,
char** argv)
![](http://static.javashuo.com/static/loading.gif)
{
int i=atoi(argv[2]);
char *buf;
![](http://static.javashuo.com/static/loading.gif)
buf= read_line(argv[1],i);
![](http://static.javashuo.com/static/loading.gif)
printf(
"%s\n",buf);
return 0;
![](http://static.javashuo.com/static/loading.gif)
}