【求助】C程序--输出文件的末尾行(对最佳结果追加30分)

来源:百度知道 编辑:UC知道 时间:2024/05/21 13:44:55
请朋友帮帮忙 用标准C写下 谢谢!

【问题描述】
命令 tail用来打印文件中最后n行。
命令格式为:tail [-n] filename,其中:
-n :n表示需要打印的行数,省略时n的值为10。
filename :给定文件名。
如,命令tail -20 example.txt 表示打印文件example.txt的最后20行。用C语言实现该程序,该程序应具有一定的错误处理能力,如能处理非法命令参数和非法文件名。(提示:使用命令行参数)
【输入形式】
tail [-n] filename,其中:-n :n表示需要打印的行数,省略时n的值为10。
filename :给定文件名。
【输出形式】

打印文件filename的最后n行
【输入样例】
命令:tail -2 tail.in
tail.in文件内容为:
Alcatel provides end-to-end solutions.
It enables enterprises to deliver content to any type of user.
lcatel operates in 130 countries.
Alcatel focus on optimizing their service offerings and revenue streams.

【输出样例】
屏幕将显示:
lcatel operates in 130 countries.
Alcatel focus on optimizing their service offerings and revenue streams.

【样例说明】
使用tail -2 tail.in输出文件tail.in的最后两行。
朋友,你的程序在我的系统里运行 有问题,我不懂不知道怎么改,有些格式可以按照题目的您在改一下吗??还有这个程序要怎么调试?????

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LENGTH 100
#define MAX_SIZE 200

void printLastLine( FILE *fp, int n );
void printHelp();

int main( int argc, char *argv[] )
{
int i = 0;
FILE *fp = NULL;

switch( argc )
{
case 2 :
if ( ( fp = fopen( argv[1], "r" ) ) == NULL )
{
printf( "can't open %s!\n", argv[1] );
exit(1);
}

printLastLine( fp, 10 );

fclose( fp );
break;

case 3 :
if ( argv[1][0] != '-' )
{
printHelp( argv[0] );
exit(1);
}

for ( i = 1; argv[1][i] != '\0' && argv[1][i] >= '0' && argv[1][i] <= '9'; i++ );

if ( argv[1][i] != '\0' )
{
printHelp( argv[0] );
exit(1);
}

i