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);
  }
}

Recommended Answers

All 4 Replies

post the file. Does one record consist of two or more lines in the file? If not, then why use %?

post the file. Does one record consist of two or more lines in the file? If not, then why use %?

Yes records consist of varying numbers of lines, each record terminated by a single %

If each record is terminated by '%', why are you testing the first character of the line read?

We still need to see some example records. For example, might it be something like this?

one
one-two
one-three
%
two
two-two
two-three
%
etc
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.