CMPSC 311, Spring 2013, Midterm Exam 2, Sample questions for review



Write a code sequence to open a file, read its contents, determine whether the file contains a line of text longer than 80 characters (not including the line-terminating newline character), then print "yes" or "no" as appropriate, and close the file.  Partial credit for pseudo-code is possible.

Note that "yes" or "no" should be printed only once.  Assume the usual Unix text file convention for end-of-line, and ASCII characters.

Solution

There are many ways to write a correct answer to this problem.  Starting with pseudocode helps in most cases, by concentrating your attention and reducing disorganization.

Here is an example of a correct answer, although not a full-credit answer because some of it is still pseudocode.

FILE *f = fopen("filename", "r");
// verify f != NULL

char buf[MAXLINE];
  // MAXLINE should be larger than 82, so we can hold the '\n' and '\0'
  // from fgets()
int found = 0;

while (fgets(buf, MAXLINE, f) != NULL) {
  int n = strlen(buf);
  if (n > 81 || buf[n] != '\n')
    { found = 1; break; }
}      

if (found) printf("yes\n");
else       printf("no\n");

if (fclose(f) != 0)
  { /* error */ }


Assorted mistakes:



Explain why this function has a serious bug, or displays a serious flaw in the programmer's logic.  Its intent is to allocate memory.

char * blat(size_t n)
{
  char a[n];
  /* assign values to elements of a[], or maybe not */
  return a;
}

Some answers, better to worse
Notes
Assorted wrong answers



Explain why this function has a serious bug, or displays a serious flaw in the programmer's logic.  Its intent is to allocate and initialize memory.

void blat(size_t n)
{
  char *a = malloc(n);
  for (int i = 0; i < n; i++)
    a[i] = 0;
}

Some answers, better to worse
Notes
Assorted wrong answers