Topic : Standart C Library for Unix
Author : James Rogers
Page : << Previous 5  Next >>
Go to page :


the stream into the string until the new line character or end-of-file marker is reached.  Never use this function.  Use fgets instead.  There is no bounds checking to see if the returned string fits into the space allowcated for it.  Many applications have been used as security holes in the past based on overwriting the end of a string.

fgets reads at most n characters from the stream into the string.

    char s[1024];
    FILE *stream;
    if((stream = fopen ("filename", "r")) != (FILE *)0) {
       while((fgets(s, 1023, stream)) != (char *)0 ) {
         <process each line>
       }
    } else {
        <do fopen error handling>
    }

To write a string to a stream,

    int  puts(const char *s);
    int fputs(const char *s, FILE *stream);


const char *s
FILE *stream is an already existing stream.

Returns a non-negative value upon success.  Returns an EOF on a write error.

puts writes the string pointed to by s to the stream STDIO and appends a new-line to the end.  The terminating null character is not written to the stream.

    char s[1024];
    FILE *stream;
    strcpy(s,"a typical string");
    if((stream = fopen ("filename", "w")) != (FILE *)0) {
       if(puts(s, stream) == EOF ) {
         <handle error on write>
       }
    } else {
        <handle error on open>
    }


fputs writes the string pointed to by s to the named stream.  The terminating null character is not written to the stream.

    char s[1024];
    FILE *stream;
    strcpy(s,"a typical string");
    if((stream = fopen ("filename", "w")) != (FILE *)0) {
       if(fputs(s, stream) == EOF ) {
         <handle error on write>
       }
    } else {
        <handle error on open>
    }


To read/write between arrays and streams,

    size_t fread(const void *ptr, size_t size, size_t nmemb, FILE *stream);
    size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);


const void *ptr is a pointer to the array.
size_t size is the size of each element of the array
size_t nmemb is the number of elements to be processed.
FILE *stream is an already existing stream.

fread reads into the array pointed to by ptr, no more than nmemb elements of the size size, from the stream.  The function returns the number of elements that were successfully read, this value can be less than what was requested, if the function encounters a read failure or an EOF.  A read failure leaves the element that failed in an undefine state. If size or nmemb are zero then the function returns a zero.

    int a[10];
    FILE *stream;
    if((stream = fopen ("filename", "r")) != (FILE *)0) {
        if (fread(a, sizeof(a), 10, stream) < 10){
            <handle a read error>
        }
    } else {
        <handle a file open error>
    }


fwrite writes from the array pointed to by ptr, no more than nmeb elements of the size size, to the stream.  The function returns the number of elements successfully written, which should match nmemb only if no write errors were encountered.

    int a[10];
    FILE *stream;
    if((stream = fopen ("filename", "w")) != (FILE *)0) {
        if (fwrite(a, sizeof(a), 10, stream) < 10){
            <handle a write error>
        }
    } else {
        <handle a file open error>
    }



Part Three: <stdio.h> formatted input/output


The last article was on character I/O in the standard input/output library <stdio.h>.  This article is on formatted input and output.   I am assuming a knowledge of c programming on the part of the reader.  There is no guarantee of accuracy in any of this information nor suitability for any purpose.

As an example of formatted input output we will read in a file containing a number and a label.  We will subtotal the items by label and print out the subtotal with its label along with a total for all subtotals.  The example is example3.c and the data file is example3.dat.

The code examples given for each function will typically not run unless the the <angle bracked> items are replaced with real code.  Normally these are items that have to be treated differently depending on what you are trying to do.  As always, if you see an error in my documentation please tell me and I will correct myself in a later document.  See corrections at end of the document to review corrections to the previous articles.

Formatted Output

#include <stdio.h>
int   printf(const char *format, ...);
int  fprintf(FILE *stream, const char *format, ...);
int  sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const  char  *format, ...);

const char *format is a format that will be used to process the following arguments.
... is a variable number of arguments that must match the number of arguments used in const char *format.
FILE *stream is a previously fopened stream.
char *str is a string.
size_t size is the maximum size of string that will be produced, any excess is lost.
printf is used to print out a formatted sequence of characters to standard out.

int x=5;
printf("We have %d apples.\n", x);


This example prints to stdout "We have 5 apples." with a newline following.

fprintf is used to print out a formatted sequence of characters to a file.

fprintf(stderr, "DEBUG\t%s\t%s\t%f",  dateString, messageString, errorNumber);

Could print to stderr, "DEBUG    199808291055    you are here    1234.4567" followed by a newline.

sprintf is used to print out a formatted sequence of characters to a character array.

float x=99.1234;
sprintf(string, "%d", x)


This would create a string that contained the characters '9', '9', '.', '1','2','3','4'.   This is the reverse to the atoi function that we will cover next month.

snprint is used to print out a formatted sequence of characters to a string.
  
float x=99.1234;
returnValue=sprintf(string, 4, "%d", x)


This will create a string with the characters '9','9','.','1', returnValue will contain a -1 because the field was truncated.

Formatted Input

#include <stdio.h>
int  scanf( const char *format, ...);
int fscanf( FILE *stream, const char *format, ...);
int sscanf( const char *str, const char *format, ...);


const char *format is a format that will be used to process the following arguments.
... is a variable number of arguments that must match the number of arguments used in const char *format.
FILE *stream is a previously fopened stream.
char *str is a string.
size_t size is the maximum size of string that will be produced, any excess is lost.
These functions return an EOF on a read error, or the number of items that were converted, zero or more.

scanf will read in a format from standard input.

scanf("%f%2d%d", float1, int1, int2)

with the following on stdin:

12.34 4567

will set float1=12.34, int1=45 and int2=67.

fscanf will read in a format from the given stream.

fscanf(stdin,"%f%2d%d", float1, int1, int2)

This example is equivilent to the scanf example.

sscanf will read a format from the given string.

sscanf(string, "%f%2d%d", float1, int1, int2)

Will scan string for the float and decimal values.

Format Strings

The format will look like the above examples.  A more general desription is as follows:

A format string contains zero or more of the following

Page : << Previous 5  Next >>