I Have the following skeleton c code, I want to be able to open the file for reading and write some of its contents to the screen. rather than being hard coded into the program, the name of the file to be opened and read will be given a command line argument. I am trying to modify it so that it finds the appropriate record from the file and prints it out. eg the 50th record. records are terminated with a %.
This is what I have so far....
#include <stdio.h>
#include <stdlib.h>
const int lineLength = 1024;
int main(int argc, char *argv[])
{
if (argc != 3)
{
fprintf(stderr, "Usage: read-rec <n> <file>\n");
exit(-1);
}
int n = atoi(argv[1]); // convert to int: argv[1] is in string form
char *f = argv[2];
FILE *from;
if ((from = fopen(f, "r")) == NULL)
{
fprintf(stderr, "Cannot open file, '%s', for reading; exiting\n", f);
exit(-1);
}
/* now start reading the file */
int recsSeen = 0;
char line[lineLength];
while (fgets(line, lineLength, from) != NULL)
{
/*
we've read a line of the file; now we need to count which record
it is by virtue of the number of '%'s we've seen.
*/
if (line[0] == '%')
recsSeen++;
/* when we want to print a line to the "screen" we would use: */
fprintf(stdout, "%s", line);
}
}