Practice with File Handling

Assignments


Assignment A-13.1

What is the difference between scanf( ) and gets( )?


Assignment A-13.2

Write a program that reads two command line arguments. The first one is a string and the second one a file name. The program then should search the file, printing all lines that contain the string. Use fgets( ) rather than get( ). Hint: use the function strstr( ).


Assignment A-13.3

Find the error(s) in the following program segment;

int main ()
{
   int* fp;
   int, k;
   fp = fopen ("pizza");
   for(k =0; k <30; k++)
   printf ("Jill likes pizza.\n", fp);
   fclose ("pizza");
   return0;
}


Assignment A-13.4

Suppose we have these statements in a program

FILE *fp1, *fp2; char ch; 

fp1 = fopen ("file1", "r");
fp2 = fopen ("file2", "w");

Assuming that both files opened successfully, supply the missing arguments in the following function calls:

a) fscanf (___, "%c", &ch);

b) fprintf (___, "%c\n", ch);

c) fclose (___); /* close the file for writing */

Assignment A-13.5

What is the output of the following program? Include in your answer the contents of any files created.

int main()
{
   FILE *fp;
   int k;
   char ch;
   fp = fopen ("file.txt","w");
   if(fp == NULL)
   {
      printf("Error opening file.\n");
      return1;
   }
   else
   {
      for(k =2; k <20; k+=2)
      fprintf (fp,"%3d", k);
      fclose (fp);
      fp = fopen ("file.txt","r");
      while((ch = fgetc(fp))!= EOF)
      {
         if(ch ==' ')
         fputc ('*', stdout);
         elseif(ch !='1')
         fputc (ch, stdout);
         else
         {
            putchar ('\n');
            putchar (ch);
         }
      }
   }
return0;
}


Assignment A-13.6

Based on the statement below:

fp = fopen ("names.dat", "w");

a) What is the statement to declare this file pointer?

b) Write a statement that writes the string "Rock my heart" to the file.

c) Write a statement that closes the file.


Assignment A-13.7

With the following declarations:

double x;

int n;

char ch, str[40];

Indicate the contents of the variables after each of the following input operations are performed. Assume that the file accessed by fp consists of the data given and that each statement below occurs at the beginning of the program immediately after a statement that opens the file.

123 3.145 xyz<newline>35 z<newline>

a) fscanf (fp, "%d%lf%s%c", &n, &x, str, &ch);

b) fscanf (fp, "%d%lf", &n, &x);
fscanf (fp, "%s %c", str, &ch);

c) fscanf (fp, "%lf%d%c%s", &x, &n, &ch, str);

d) Write the statement that opens this file.


Assignment A-13.8

What does this program do?

int main()
{
   FILE *fp;
   char str[80];
   fp = fopen ("file.txt","w");
   if(fp == NULL)
   {
      printf("Error opening file.\n");
      return1;
   }
   do
   {
       printf ("Enter a string (ENTER to quit): ");
       gets (str);
       strcat(str,"\n");
       fputs (str,fp);
   }
while(*str !='\n'); return0; }


Assignment A-13.9

What does this program do? Modify it so that it does the same thing for a file rather than for what is printed to the screen.

#define STOP '|'
int main()
{
   char c;
   int n_chars, n_lines, n_words;
   int wordflag =0;
   n_chars = n_lines = n_words =0;
  while((c = getchar())!= STOP)
{
n_chars++;
if(c =='\n')
n_lines++;
if(c !=' '&& c !='\n'&& c !='\t'&& wordflag ==0)
{
   wordflag =1;
   n_words++;
}
if((c ==' '|| c =='\n'|| c =='\t')&& wordflag ==1)
wordflag =0;
}
n_lines++;
printf ("characters = %d, words = %d, lines = %d\n", n_chars, n_words,
n_lines);
return0;
}


Assignment A-13.10

Based on the file data.txt, create a program that reads the file and outputs its content to the screen, with the appropriate headers (ex: Name, ID, Quiz 1, Quiz 2, Quiz 3, Quiz 4, Exam). Allow the user to view the data in "chunks", asking him to press any key in order to see the next "chunk". At the end, print a statistics table, showing the average, lowest, and highest scores on each quiz/exam.


Assignment A-13.11

What is the output of the following program segment?

char*p;
p = strchr ("this is a test",'s');
printf ("%s\n",p);


Assignment A-13.12

What is the output of the following program segment?

char*p;
p = strstr ("this is a test","is");
printf ("%s\n",p);


Assignment A-13.13

What is the output of the following program segment?

int len;
len = strspn ("this is a test","isht");
printf ("%d\n",len);


Assignment A-13.14

What is the output of the following program segment?

char*p;
p = strtok ("The summer soldier, the sunshine patriot"," ");
printf ("%s\n",p);
do
{
p = strtok (NULL,",");
if(p)
printf ("%s\n",p);
}
while(p);


Assignment A-13.15

What is the output of the following program segment?

char s1[10]="abcdefghi";
char s2[10]="ace";
char s3[10]="defg";
char s4[10];
strcpy (s4, s2);
strcat (s4, s3);
strncat (s4, s1,sizeof(s4)-1- strlen (s2));
printf ("%s\n", s4);


Assignment A-13.16

What is the output of the following program segment?

int d1, d2, d3, d4;
char s1[10]="abcdefghi";
char s2[10]="ace";
char s3[10]="defg";
d1 = strspn (s1, s2);
d2 = strspn (s1, s3);
d3 = strcspn (s1, s2);
d4 = strcspn (s1, s3);
printf ("%d %d %d %d\n", d1, d2, d3, d4);


Assignment A-13.17

What is the output of the following program?

int main()
{
struct gas
{
float distance;
float gals;
float mpg;
}
trip[3]={{1000.0,40.0,0},{400.0,15.0,0},{500.0,20.0,0}};
struct gas *ps = trip;
int cnt =1;
charadd[5];
while(ps <=&trip[2])
{
ps -> mpg = ps -> distance / ps -> gals;
switch(cnt)
{
case1:
strcpy (add,"st");
break;
case2:
strcpy (add,"nd");
break;
case3:
strcpy (add,"rd");
}
printf ("The %d%s calculated field is: %f\n", cnt,add, ps -> mpg);
ps++;
cnt++;
}
return0;
}


Assignment A-13.18

Given the following declaration, what is the value of *x, *(x+1), and *(x+4)?

char *x = "Life is beautiful"


Assignment A-19

Would the value of the integer dif on the program segment below be positive, negative or zero?

char s1[] = "xyzt"; char *s2 = "xyAt"; int dif;dif = strcmp (s1, s2);


Assignment A-13.20

What is the output of the following program segment?

char s1[50]="abcd";
char*s2 ="efghijklmno";
char*s3,*s4,*s5,*s6;
s3 = s1;
s4 = s2;
strcat (s1, s2);
s5 = strchr (s1,'d');
s6 = strrchr (s2,'n');
printf ("%s\n%s\n%s\n%s\n", s3, s4, s5, s6);


Assignment A-13.21

What is the output of the following program segment?

char*s1 ="uabefgnpanm";
char s2[]="ab";
char*s3 ="pan";
char s4[]="bef";
char*s5 ="panam";
char*s6,*s7,*s8,*s9;
s6 = strstr (s1, s2);
s7 = strstr (s1, s3);
s8 = strstr (s1, s4);
s9 = strstr (s1, s5);
printf ("%s\n%s\n%s\n%s\n", s6, s7, s8, s9);


Assignment A-13.22

What is the output of the following program segment?

char*s1 ="abefgnpanm";
char s2[]="ab";
char*s3 ="pan";
char s4[]="bef";
char*s5 ="panam";
int d1, d2, d3, d4;
d1 = strspn (s1, s2);
d2 = strspn (s1, s3);
d3 = strspn (s1, s4);
d4 = strspn (s1, s5);
printf ("%d\n%d\n%d\n%d\n", d1, d2, d3, d4);


Assignment A-13.23

What is the output of the following program segment?

char*a[5]={"cool","groovy","sweet",
"dreading","awesome"};
printf ("%s\n", a[0]);
printf ("%s\n",*(a+2));
printf ("%c\n",*(a[2]+2));
printf ("%s\n", a[3]);
printf ("%c\n",*(*(a+3)+4));


Assignment A-13.24

Modify the following code to use a string for the password. Use the function getch( ) to keep the password from showing up on the screen, instead type asterisks to the screen. You will need to read the characters into a character array, character by character.

int main()
{
int storedPass =11862;
int numTries =0;
int maxTries =3;
int userPass;
while(numTries < maxTries)
{
printf ("Enter the password: ");
scanf ("%d",&userPass);
numTries++;
if(userPass == storedPass)
{
printf ("Welcome to the FBI file system.\n");
break;
}
else
{
printf ("Wrong password!");
if(numTries == maxTries)
{
printf ("Locked out!\n");
exit(0);
}
elseif(numTries ==(maxTries -1))
printf ("%d more try.\n", maxTries - numTries);
else
printf ("%d more tries.\n", maxTries - numTries);
}
}
return0;
}

Source: Kishori Mundargi, https://www.peoi.org/Courses/Coursesen/cprog/cprog13x.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License.