0

我正在尝试编写一个程序,该程序将从文本文件中打印出一定数量的行。我想我有代码可以打开文件并扫描它有多少行。我只是无法打印出这些线条。(例如,打印文件的第 1 到 10 行。)

我应该把文件的所有读取都变成一个单独的方法吗?

numLines是从用户输入中提前声明的。我还想从命令行参数打开 src。不确定这是否正确实施。

编辑我正在使用的完整代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 256


int numLines = 0;
int linecount = 0;
FILE *src = NULL;
char b[MAX];
char ch;

void GetArgs (int argc, char **argv){
if(argc != 4 || argc != 2) {
    printf("Error not enough arguments to continue \n", argv[0]);
    exit(-1);

}// end if argc doenst = 4 or 2

if(argc == 2){
    src = fopen( argv[1], "r:");
    numLines=10;

}// end argc = 2

if(argc == 4){
    if (strcmp (argv[1], "-n") !=0 ){
        numLines = atoi (argv[2]);
        src = fopen (argv[3], "r");
        if ( src == NULL){
            fputs ( "Can't open input file." , stdout);
            exit (-1);
        }
        while (NULL != fgets(ch,MAX, src)){
            linecount++;
            fputs(ch, stdout);
            if (linecount == numLines){
                break;
            }
        }

    }//end of nested if
    else (strcmp (argv[2], "-n") !=0 ){
        numLines = atoi (argv[3]);
        src = fopen (argv[1], "r");
        if ( src == NULL){
            fputs ( "Can't open input file." , stdout);
            exit (-1);
        }
        while (NULL != fgets(ch,MAX, src)){
            linecount++;
            fputs(ch, stdout);
            if (linecount == numLines){
                break;
            }
        }            


    }//end of else
}//end if argc == 4

}// end GetArgs


}// end GetArgs


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



GetArgs(argc, argv);
4

2 回答 2

2
while ( fgetc(ch,MAX,src) !=EOF )

你打电话fgetcfgets. fgetc只接受一个参数:a FILE *stream

于 2012-09-11T04:57:33.410 回答
2

试试这个

FILE * src = NULL;
int linecount = 0;
int numLines = 5;
char ch[MAX];

src = fopen( argv[1], "r" );
if ( src == NULL ) {
    fputs( "Can't open input file.", stdout );
    exit(-1);
}

while(NULL != fgets(ch,MAX,src)) {
    linecount++;
    fputs(ch, stdout);

    if (linecount == numLines) {
        break;
    }
}
于 2012-09-11T05:42:48.150 回答