Practice Problems

File I/O

Notice when you get compile errors (when gcc gives you an error)
vs. errors that crash the program (run-time errors)
vs. logical errors (compile and run fine but problem with your code)
  1. Write the code to declare and open a file for reading named coba.txt
    	#include <stdio.h> 	/* Assumed on all subsequent examples */
    	...
    	FILE *f;
    	f = fopen("coba.txt", "r");
    	
  2. Write the code to declare and open a file for writing named out.txt
    	FILE *f;
    	f = fopen("out.txt", "w");
    	
  3. What is the purpose of the fclose call on a file?

    To flush the I/O buffers to the file on the disk. Also, to release system resources, since you can only have so many files open at once.

  4. What is the code to read the first line of the file (and that's it)?
    	FILE *f;
    	char buf[80];
    	f = fopen("coba.txt", "r");
    	fgets(buf, sizeof(buf), f);	/* Still contains \n */
    	
  5. Write the loop to read each line from a file.
    	FILE *f;
    	char buf[80];
    	f = fopen("coba.txt", "r");
    	while (fgets(buf, sizeof(buf), f) != NULL)
    		fputs(buf, stdout);
    	
  6. What additional argument is required when using fprintf and fscanf as opposed to printf and scanf?

    The first parameter is a FILE *.

  7. List 3 functions that can be used to read data from a file.

    fgetc fgets fscanf

  8. List 3 functions that can be used to write data to a file.

    fputc fputs fprintf

  9. Write the code to open a file named input.txt and print an error statement if there is a problem opening the file.
    	FILE *f;
    	f = fopen("input.txt", "r");
    	if (f==NULL) {
    		fprintf(stderr, "Couldn't open input.txt for reading\n");
    		exit(1);
    	}