Page 1 of 1

C FILE INPUT AND OUTPUT TUTORIAL PART 1 C FILE INPUT AND OUTPUT TUTORIAL PART 1 Rate Topic: -----

#1 Elcric  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 101
  • View blog
  • Posts: 453
  • Joined: 02-May 09

Posted 03 May 2010 - 03:39 PM

C FILE INPUT AND OUTPUT TUTORIAL PART 1


CONTENTS
• I. INTRODUCTION
• II. VOCABULARY
• III. WRITING TO A FILE
• IV. READING FROM A FILE
• V. EXAMPLE PROGRAM
• VI. REFERENCES

WHAT YOU WILL LEARN IN THIS TUTORIAL

1. You will learn C input and output vocabulary.

2. You will learn how to write to a binary file.

3. You will learn how to read from a binary file.

• I. INTRODUCTION

Hello; nice to meet you. Welcome to the “C File Input and Output Tutorial Part 1.”

During this tutorial we will discuss the library functions C uses for file input and output. The prototypes for these functions are in the C header files; for example, <stdio.h>.

C++ includes the entire C language; therefore, all C programs, with a few minor exceptions, are also C++ programs.

The C code examples shown in the tutorial were written using the Microsoft Visual C++ 2008 Express Edition Integrated Development Environment (IDE) and the “C99 subset.”

• II. VOCABULARY

A. What is a field?

A field is a group of characters that conveys meaning such as a field representing a color of light.

B. What is a record?

A record is a group of related fields.

C. What is a stream?

A stream is a logical device.

Streams are device independent mental abstractions. When you use scanf() and stdin you are using a keyboard file stream. When you use printf() and stdout you are using a screen file stream.

A stream is a flow of related records. There are two types of streams: text and binary. A sequence of characters is a text file stream. A sequence of bytes is a binary file stream.

D. What is a FILE pointer?

A FILE pointer is used to enable the program to keep track of the stream being accessed, and to let the compiler perform input and output functions.

A program opens a file stream by calling a standard library function. The library function returns a FILE pointer. The file pointer is a pointer to a structure of type FILE. The file pointer points to the unique memory address of a file.

The syntax for a FILE pointer is as follows:

FILE *fp;



E. What is a file?

A file is an actual device.

A file is a container you can both read from and write to.

F. What is a header file?

The header files contain prototypes for the file input and output functions; and macros.

Prototypes declare functions before they are used.

The syntax for a function prototype is as follows:

type function_name(type parameter_name1, type parameter_name2,…, type parameter_nameN,);



When a function has no parameters, use void inside the parameter list.

type function_name(void);



G. What is POD?

POD is Plain Old Data. For example, in the case of a POD structure, the structure would contain no pointers and all members would be of a fixed size.

H. What is a Library?

C provides the basic functions you need to get started. However, you have to code everything else yourself.

When you notice you are rewriting the same code over and over take the time to turn that code into a generic library function.

A library consists of two parts: a header file and the actual code file. The library header file uses quotes instead of the symbols
< and >, which are only used for system libraries.

Library C function calls should always pass arguments by value. In other words use regular function variables, do not use function pointers. This is done to ensure that only local “copies” of the values of the arguments are passed to the library function. Therefore, all changes made to the arguments in the local copy of the library function are only made to the local copy of the arguments and not to the original arguments themselves.

• III. WRITING TO A FILE

Writing to a file requires 3 steps:

A. Open the file.

To open a file use the fopen function, which returns a FILE pointer.

The open operation return pointer associates a stream with a specific file. If the file can not be opened, the return pointer is set to the value NULL.

The syntax for opening a file is as follows:

FILE *fopen(const char *filename, const char *mode);



The filename is a string containing the name of the file to be opened.

The mode is a string containing the way the file will be used.

Text file modes are as follows:

r Open file for reading. File must exist. NULL pointer returned if file does not exist.

w Open for writing. If file does not exist it is created. If file does exist it will be overwritten.

a Open file for appending. If file does not exist it is created. Appends if file exists.

r+ Open file for reading and writing. File must exist. Starts at beginning of existing file.

w+ Open file for reading and writing. If file does not exist it is created. Overwrites existing file.

a+ Open file for reading and writing. If file does not exist it is created. Appends if file exists.

Binary file modes are as follows:

rb Open file for reading. File must exist. NULL pointer returned if file does not exist.

wb Open for writing. If file does not exist it is created. If file does exist it will be overwritten.

ab Open file for appending. If file does not exist it is created. Appends if file exists.

r+b Open file for reading and writing. File must exist. Starts at beginning of existing file.

w+b Open file for reading and writing. If file does not exist it is created. Overwrites existing file.

a+b Open file for reading and writing. If file does not exist it is created. Appends if file exists.

For binary File I/O you use fread and frwrite.

When typing a file path, type double back-slashes. For example, typing "j:\folder\example1.bin" will not work. You have to type "j:\\folder\\example1.bin". The folder has to exist. The program will crash if the folder does not exist.

An example of opening a binary file for writing is as follows:

FILE *fp;
fp=fopen(“j:\\examples\\example1.bin”,”wb”);



This code will open the binary file named example1.bin on drive j: in folder examples for writing. If file does exist it will be overwritten. If the file does not exist it will be created.

Always test to make sure the file opened before you try to write to the file.

An example of testing whether a file did not open is as follows:

if ((fp = fopen ("j:\\examples\\example1.bin","wb")) == NULL)
{
printf ("ERROR MESSAGE!  File could not be opened!\n");
}



Once you know the file opened properly, use the FILE return pointer to tell the compiler to perform input and output functions on the file.

Use fread() and fwrite() for binary file fixed-length record I/O; for example:

size_t fwrite(const void *buffer, size_t num_bytes, size_t count, FILE *fp);



fwrite() takes four arguments:

1. const void * buffer

The first argument is a pointer to the name of the array or the address of the structure you want to write to the file.

2. size_t num_bytes

The second argument is the size of each element in bytes.

For example, if you have an array of characters, you would read the array in one byte at a time. Therefore, num_bytes would be one.

3. size_t count

The third argument is the count of the number of elements you want to write.

4. FILE * fp

The fourth argument is the stream file pointer.

B. Do all the writing.

An example of writing to a binary file is as follows:

//  write to binary file
			
			FILE *fp;
			fp=fopen("j:\\examples\\example1.bin", "wb");
			if (fp == NULL)
			{
			printf ("  ERROR MESSAGE!  Binary file could not be opened!\n\n\n\n");
			}else
			{
				printf("  Binary file opened!\n\n\n\n");
				fwrite(&write, sizeof(write[0]), sizeof(write)/sizeof(write[0]), fp);
				printf("  %s character string array was written to the binary file.\n\n\n\n", write);  
			}

			int returncode;
			returncode = fclose (fp);
			
			if (returncode == 0)
			{
				printf ("  Binary file closed!\n\n\n\n");
			}else
			{
				printf ("  ERROR MESSAGE!  Binary file did not close!\n\n\n\n");
			}



C. Close the file.

Always close a file as soon as you are done using it. The syntax for closing a file is as follows:

int returncode;

returncode = fclose (fp);



If returncode == 0; the file pointed to by fp closed.

If returncode != 0; the file pointed to by fp did not close.

Always test to make sure the file closed. Zero is returned if it closed. EOF is returned if it did not close.

An example of testing whether a file closed is as follows:

if (fclose(fp) != 0)
{
printf ("ERROR MESSAGE!  File did not close!\n");
}



if fclose(fp) == 0; the file pointed to by fp closed.

if (fclose(fp) != 0); the file pointed to by fp did not close.

• IV. READING FROM A FILE

Reading from a file requires 3 steps:

A. Open the file.

Test to make sure the file opened before you read the file.

//  read from binary file

			FILE *fpRead;
			fpRead=fopen("j:\\examples\\example1.bin", "rb");
			if (fpRead == NULL)
			{
				printf ("  ERROR MESSAGE!  Binary file could not be opened!\n\n\n\n");
			}else
			{
				printf ("  Binary file opened!\n\n\n\n");



B. Do all the reading.

The input file that we are opening for reading must already exist.

fread(&read, sizeof(read[0]), sizeof(read)/sizeof(read[0]), fpRead);



C. Close the file.

The syntax for closing a file is as follows:

printf("  %s character string array was read from the binary file.\n\n\n\n", read);
			}
			
			int returncodeRead;
			returncodeRead = fclose (fpRead);
			
			if (returncodeRead == 0)
			{
				printf("  Binary file closed!\n\n\n\n");
			}else
			{
				printf("  ERROR MESSAGE!  Binary file did not close!\n\n\n\n");
			}



• V. EXAMPLE PROGRAM

//*******************************************
//  C FILE INPUT AND OUTPUT TUTORIAL PART 1   
//*******************************************  

#include<conio.h>     //  contains function prototypes
#include<stdio.h>     //  standard I/O header file
#include<string.h>    //  string handling
#include<windows.h>   //  keybd_event()

void ShowTime(void);
void AltEnter(void);
void DateTime(void);
void menu(void);

//**********************************

int main(int argc, char *argv[])
{
	ShowTime(); 
	menu();     
		   
	return EXIT_SUCCESS;
}

//**********************************

void ShowTime(void)
{
	AltEnter();
	system("COLOR 1F");

	return;
}

void AltEnter(void)
{
    keybd_event(VK_MENU,
                0x38,
                0,
                0);
    keybd_event(VK_RETURN,
                0x1c,
                0,
                0);
    keybd_event(VK_RETURN,
                0x1c,
                KEYEVENTF_KEYUP,
                0);
    keybd_event(VK_MENU,
                0x38,
                KEYEVENTF_KEYUP,
                0);
    return;
}

void DateTime(void)
{
	printf("\n");
	printf("\n");
	printf("\n");
	printf("                              ");
	printf(__DATE__);
	printf("    ");
	printf(__TIME__);
	printf("\n");
	printf("\n");

	return;
}

void menu(void)
{
	system("CLS");  
	DateTime();
	printf("\n\n                      C FILE INPUT AND OUTPUT TUTORIAL PART 1\n\n\n\n");
	
	printf("  0  EXIT\n\n");
	printf("  1  Write a character string array to a binary file\n\n");
	printf("     and then read that character string array from the same binary file.\n\n\n");
	printf("\n\n  Please type your menu selection; for example, 0 to EXIT.\n\n  ");

	char menuSelection;
	menuSelection = getch();

	switch(menuSelection)
	{
		case '0':
			break;

		case '1':
			system("CLS");  
			DateTime();
			printf("\n\n                      C FILE INPUT AND OUTPUT TUTORIAL PART 1\n\n\n\n");

			char write[10]="ELEPHANTS";

			char read[10];
			for (int i=0; i++; i<=10)
			{
				read[i]='\n';
			}
			
			//  write to binary file
			
			FILE *fp;
			fp=fopen("j:\\examples\\example1.bin", "wb");
			if (fp == NULL)
			{
			printf ("  ERROR MESSAGE!  Binary file could not be opened!\n\n\n\n");
			}else
			{
				printf("  Binary file opened!\n\n\n\n");
				fwrite(&write, sizeof(write[0]), sizeof(write)/sizeof(write[0]), fp);
				printf("  %s character string array was written to the binary file.\n\n\n\n", write);  
			}

			int returncode;
			returncode = fclose (fp);
			
			if (returncode == 0)
			{
				printf ("  Binary file closed!\n\n\n\n");
			}else
			{
				printf ("  ERROR MESSAGE!  Binary file did not close!\n\n\n\n");
			}

			//  read from binary file

			FILE *fpRead;
			fpRead=fopen("j:\\examples\\example1.bin", "rb");
			if (fpRead == NULL)
			{
				printf ("  ERROR MESSAGE!  Binary file could not be opened!\n\n\n\n");
			}else
			{
				printf ("  Binary file opened!\n\n\n\n");
				fread(&read, sizeof(read[0]), sizeof(read)/sizeof(read[0]), fpRead);
				printf("  %s character string array was read from the binary file.\n\n\n\n", read);
			}
			
			int returncodeRead;
			returncodeRead = fclose (fpRead);
			
			if (returncodeRead == 0)
			{
				printf("  Binary file closed!\n\n\n\n");
			}else
			{
				printf("  ERROR MESSAGE!  Binary file did not close!\n\n\n\n");
			}
 										
			printf("\n\n  Type any key to continue.\n\n  ");

			char screenOpen;
			screenOpen = getch();  //  keeps screen open until a key is pressed

			menu();     
			break;																								
	}
}



• VI. REFERENCES

The C Programming Language by Brian Kernighan and Dennis Ritchie (Englewood Cliffs, N.J.: Prentice-Hall, 1978).

C++: The Complete Reference, Fourth Edition by Herbert Schildt (Berkeley, California: McGraw-Hill/Osborne, 2003).


Is This A Good Question/Topic? 2
  • +

Page 1 of 1