Tuesday, 13 May 2014

C - File I/O

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Last chapter explained about standard input and output devices handled by C programming language. This chapter we will see how C programmers can create, open, close text or binary files for their data storage.
A file represents a sequence of bytes, does not matter if it is a text file or binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. This chapter will take you through important calls for the file management.

Opening Files

You can use the fopen( ) function to create a new file or to open an existing file, this call will initialize an object of the type FILE, which contains all the information necessary to control the stream. Following is the prototype of this function call:
FILE *fopen( const char * filename, const char * mode );
Here, filename is string literal, which you will use to name your file and access mode can have one of the following values:
ModeDescription
rOpens an existing text file for reading purpose.
wOpens a text file for writing, if it does not exist then a new file is created. Here your program will start writing content from the beginning of the file.
aOpens a text file for writing in appending mode, if it does not exist then a new file is created. Here your program will start appending content in the existing file content.
r+Opens a text file for reading and writing both.
w+Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist.
a+Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
If you are going to handle binary files then you will use below mentioned access modes instead of the above mentioned:
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Closing a File

To close a file, use the fclose( ) function. The prototype of this function is:
 int fclose( FILE *fp );
The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This function actually, flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provide by C standard library to read and write a file character by character or in the form of a fixed length string. Let us see few of the in the next section.

Writing a File

Following is the simplest function to write individual characters to a stream:
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream:
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file. Try the following example:
#include 

main
()
{
FILE
*fp;

fp
= fopen("/tmp/test.txt", "w+");
fprintf
(fp, "This is testing for fprintf...\n");
fputs
("This is testing for fputs...\n", fp);
fclose
(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in next section.

Reading a File

Following is the simplest function to read a single character from a file:
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error it returns EOF. The following functions allow you to read a string from a stream:
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file but it stops reading after the first space character encounters.
#include 

main
()
{
FILE
*fp;
char buff[255];

fp
= fopen("/tmp/test.txt", "r");
fscanf
(fp, "%s", buff);
printf
("1 : %s\n", buff );

fgets
(buff, 255, (FILE*)fp);
printf
("2: %s\n", buff );

fgets
(buff, 255, (FILE*)fp);
printf
("3: %s\n", buff );
fclose
(fp);

}
When the above code is compiled and executed, it reads the file created in previous section and produces the following result:
1 : This
2: is testing for fprintf...

3: This is testing for fputs...
Let's see a little more detail about what happened here. First fscanf() method read just This because after that it encountered a space, second call is for fgets() which read the remaining line till it encountered end of line. Finally last call fgets() read second line completely.

Binary I/O Functions

There are following two functions, which can be used for binary input and output:
size_t fread(void *ptr, size_t size_of_elements, 
size_t number_of_elements, FILE *a_file);

size_t fwrite(const void *ptr, size_t size_of_elements,
size_t number_of_elements, FILE *a_file);
Both of these functions should be used to read or write blocks of memories - usually arrays or structures.

C - Preprocessors
The C Preprocessor is not part of the compiler, but is a separate step in the compilation process. In simplistic terms, a C Preprocessor is just a text substitution tool and they instruct compiler to do required pre-processing before actual compilation. We'll refer to the C Preprocessor as the CPP.
All preprocessor commands begin with a pound symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in first column. Following section lists down all important preprocessor directives:
DirectiveDescription
#defineSubstitutes a preprocessor macro
#includeInserts a particular header from another file
#undefUndefines a preprocessor macro
#ifdefReturns true if this macro is defined
#ifndefReturns true if this macro is not defined
#ifTests if a compile time condition is true
#elseThe alternative for #if
#elif#else an #if in one statement
#endifEnds preprocessor conditional
#errorPrints error message on stderr
#pragmaIssues special commands to the compiler, using a standardized method

Preprocessors Examples

Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability.
#include 
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file. The next line tells CPP to get myheader.h from the local directory and add the content to the current source file.
#undef  FILE_SIZE
#define FILE_SIZE 42
This tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
This tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
/* Your debugging statements here */
#endif
This tells the CPP to do the process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation.

Predefined Macros

ANSI C defines a number of macros. Although each one is available for your use in programming, the predefined macros should not be directly modified.
MacroDescription
__DATE__The current date as a character literal in "MMM DD YYYY" format
__TIME__The current time as a character literal in "HH:MM:SS" format
__FILE__This contains the current filename as a string literal.
__LINE__This contains the current line number as a decimal constant.
__STDC__Defined as 1 when the compiler complies with the ANSI standard.
Let's try the following example:
#include 

main
()
{
printf
("File :%s\n", __FILE__ );
printf
("Date :%s\n", __DATE__ );
printf
("Time :%s\n", __TIME__ );
printf
("Line :%d\n", __LINE__ );
printf
("ANSI :%d\n", __STDC__ );

}
When the above code in a file test.c is compiled and executed, it produces the following result:
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1

Preprocessor Operators

The C preprocessor offers following operators to help you in creating macros:

Macro Continuation (\)

A macro usually must be contained on a single line. The macro continuation operator is used to continue a macro that is too long for a single line. For example:
#define  message_for(a, b)  \
printf
(#a " and " #b ": We love you!\n")

Stringize (#)

The stringize or number-sign operator ('#'), when used within a macro definition, converts a macro parameter into a string constant. This operator may be used only in a macro that has a specified argument or parameter list. For example:
#include 

#define message_for(a, b) \
printf
(#a " and " #b ": We love you!\n")

int main(void)
{
message_for
(Carole, Debra);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Carole and Debra: We love you!

Token Pasting (##)

The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate tokens in the macro definition to be joined into a single token. For example:
#include 

#define tokenpaster(n) printf ("token" #n " = %d", token##n)

int main(void)
{
int token34 = 40;

tokenpaster
(34);
return 0;
}
When the above code is compiled and executed, it produces the following result:
token34 = 40
How it happened, because this example results in the following actual output from the preprocessor:
printf ("token34 = %d", token34);
This example shows the concatenation of token##n into token34 and here we have used both stringizeand token-pasting.

The defined() Operator

The preprocessor defined operator is used in constant expressions to determine if an identifier is defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). The defined operator is specified as follows:
#include 

#if !defined (MESSAGE)
#define MESSAGE "You wish!"
#endif

int main(void)
{
printf
("Here is the message: %s\n", MESSAGE);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Here is the message: You wish!

Parameterized Macros

One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number as follows:
int square(int x) {
return x * x;
}
We can rewrite above code using a macro as follows:
#define square(x) ((x) * (x))
Macros with arguments must be defined using the #define directive before they can be used. The argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between and macro name and open parenthesis. For example:
#include 

#define MAX(x,y) ((x) > (y) ? (x) : (y))

int main(void)
{
printf
("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
When the above code is compiled and executed, it produces the following result:

0 comments:

Post a Comment