Example: goto

The following example, for Windows platforms, opens a file and reads it into a buffer. If file errors occur during the process, goto escapes the enclosing loop to code which prints an error message and exits the function.

To ensure the goto statement is executed, make sure the file c:\xyzpqi.txt does not exist. This causes fopen to return NULL and invoke the goto statement. To see the jump clearly, step through the program in VuGen by pressing the F10 key.

#include <stdio.h>
    int count, total = 0;
    char buffer[1000];
    FILE* file_stream;
    char * filename = "c:\\xyzpqi.txt";
    // Open the file with read access 
    if ((file_stream = fopen(filename, "r")) == NULL)
        goto file_error;
    // Read until end of file 
    while (!feof(file_stream)) {
   // Read 1000 bytes while maintaining a running count 
        count = fread(buffer, sizeof(char), 1000, file_stream);
        lr_output_message ("%3d read", count);
   // Check for file I/O errors
        if (ferror(file_stream)) 
            goto file_error;
  // add up actual bytes read 
        total += count; 
    }
  // Display final total 
    lr_output_message ("Total number of bytes read = %d", total);
 // Close the file stream 
    if (!fclose(file_stream)) 
        return 0;
        file_error:
        lr_error_message ("Error in file %s", filename);
Example: 
                Output:
Action.c(35): Error -17999 : Error in file c:\xyzpqi.txt