I’m trying to code a program that will print out a certain number of lines from a text file. I think I have the code to open the file and to scan it for how many lines it has. I’m just having trouble printing out the lines. (For example, printing lines 1 through 10 of a file.)
Should I make all the reading of the file into a separate method?
numLines is declared earlier from user input.
Also I wanted to make the src open from a command line argument. Unsure if that is implemented correctly.
EDIT COMPLETE CODE IM WORKING WITH
#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);
Try this