Example: fgetc

The following example, for Windows platforms, opens a file and reads 3 characters into a buffer using fgetc.

To run the example, copy the file readme.txt from the installation's dat directory to the c drive, or copy another file and change the value of filename.

#include <stdio.h>
    #define NUM_CHARS 3
    int i, total = 0;
    char buffer[100], ch;
    FILE* file_stream;
    char * filename = "c:\\readme.txt";
    if ((file_stream = fopen(filename, "r")) == NULL) {
        lr_error_message ("Cannot open %s", filename);
        return -1;
    }
    for (i=0; (i<NUM_CHARS) && (feof(file_stream) == 0); i++) {
// Read in the next character 
        ch = fgetc(file_stream); 
// Place the new char at the end of the buffer 
        buffer[i] = ch; 
    }
    // Add null to end the buffer converting it to a string 
    buffer[i] = NULL; 
    lr_output_message ("First %d characters of file %s are \"%s\"", NUM_CHARS, filename, buffer);
    if (fclose(file_stream))
        lr_error_message ("Error closing file %s", filename);
Example: 
                Output:
Action.c(34): First 3 characters of file c:\readme.txt are "***"