File Input and Output

Source Code from Notes


Example 1

Example using command line arguments to provide the filenames of the files to be opened.


#include <stdio.h>

main(int argc,char *argv[])
{
        FILE    *fin,*fout;

        if (argc != 3) {
                fprintf(stderr,"USAGE: program input_file output_file\n");
                exit(1);
        }

        if ((fin = fopen(argv[1],"r")) == NULL ) {
                fprintf(stderr,"Can't open file %s for reading\n",argv[1]);
                exit(1);
        }
        if ((fout = fopen(argv[2],"w")) == NULL ) {
                fprintf(stderr,"Can't open file %s for writing\n",argv[2]);
                exit(1);
        }

        /* rest of program */

}


Example - reading from file and detecting feof

Note: This program will read the last item in the file twice, since it does not dtect the end of file until it tries to read past it.


/*
 Program to read integers from  an input file
 specified on the command line and write them out
 as their corresponding ASCII codes in another file
*/
#include<stdio.h>

main(int argc, char *argv[])
{

        int     input;
        FILE    *fi, *fo;


        /* Check if correct number of arguments specified */
        if (argc!=3)
        {
                fprintf(stderr,"USAGE: conv_char input_file output_file\n");
                exit(1);
        }

        /*open file for reading from */
        if ((fi=fopen(argv[1],"r")) == NULL)
        {
                fprintf(stderr,"Can't open %s\n",argv[1]);
                exit(1);
        }

        /*open file for writing to */
        if ((fo=fopen(argv[2],"w")) == NULL)
        {
                fprintf(stderr,"Can't open %s\n",argv[2]);
                exit(1);
        }


        while (!feof(fi))
        {
                /*read in integer*/
                fscanf(fi, "%d", &input);

                /*write to output file as char */
                fprintf(fo,"%c\n",input);
        }
}

Corrected Program

#include<stdio.h>

main(int argc, char *argv[])
{

        int     input;
        FILE    *fi, *fo;


        /* Check if correct number of arguments specified */
        if (argc!=3)
        {
                fprintf(stderr,"USAGE: conv_char input_file output_file\n");
                exit(1);
        }

        /*open file for reading from */
        if ((fi=fopen(argv[1],"r")) == NULL)
        {
                fprintf(stderr,"Can't open %s\n",argv[1]);
                exit(1);
        }

        /*open file for writing to */
        if ((fo=fopen(argv[2],"w")) == NULL)
        {
                fprintf(stderr,"Can't open %s\n",argv[2]);
                exit(1);
        }


        fscanf(fi, "%d", &input);

        while(!feof(fi))
        {
                /*write to output file as char */
                fprintf(fo,"%c\n",input);

                /*read in integer*/
                fscanf(fi, "%d", &input);

        }
}


Back to Main Page for Lecture 8