Need for a File
The functions such as scanf () and printf () are used to read and write data from and to the terminal. These are console oriented I/O (input/output) functions which always use the terminal as the target place. Many real life problems involve large volumes of data. Then using the console oriented I/O operations pose two major problems.
• It is cumbersome and time consuming to handle large volume of data through terminals.
• The entire data is lost when either the computer is turned off or the program is terminated.
So it is necessary to have a place on the disk or any media to store the data permanently for which files are required.
The basic file operations are:
• Naming a file
• Opening a file
• Reading data from a file
• Writing data to a file
• Closing a file
For reading from or writing to files, C uses standard library functions.
To be able to use these library functions, it is necessary to include the header files containing these functions in the program. This is done by the following declaration in the beginning of the program.
#include
This tells the compiler to include all the functions given in the file stdio.h (this is the standard file containing functions for reading from or writing to files in 'C') while compiling the program.
Library Function to Open the File
Before a file is read from and written to, it must be opened.
This is done by using the library function fopen, defined as follows:
FILE *fopen (name, mode)
FILE is a special structure defined in stdio.h. Therefore all files should be declared as type FILE before they are used. FILE is a defined data type.
fopen() returns a pointer to the structure FILE
or
NULL if it fails.
This return value has to be used in subsequent reads and writes to the file. Hence, the return value must be stored in a pointer variable of type ' FILE *' as follows:
FILE *fp;
So the usage of fopen is as follows:
fp = fopen (name.mode);
where name is a character string containing the name of the file, mode is a character string which can be:
r" for opening the file in read mode
w" for opening the file in write mode
"a" for opening the file in append mode
"r+" / "w+" for opening the file in update (read and write)
mode
The following example illustrates the use of fopen() with the various opening modes.
Example:
#include
{
FILE *fp;
if ((fp = fopenfmyfile", "r"))==NULL)
{
printf("Cannot open file : myfile\n");
exit(1); }
else
printf("The file has been successfully opened\n");
}
This program segment can be used to open a file called "myfile" in the READ mode. If it is unable to open the file, the program will abort with return status of T.
Function to Close a File
Though it is not essential to close the files before termination of the program, is better to do so.
Files are automatically closed when a program terminates normally. The function fclose() has been defined to close a file in the 'C library. fclose( FILE *); The following program segment illustrates the use of fclose:
FILE * fp;
fp = fopen("myfile","r");
fclose(fp);
Functions to Read/Write a Single Character from a File
fgetc()
The fgetc() function is functionally similar to the getchar() function, about which we discussed earlier but it reads a character from a file rather than the standard input.
The syntax is :
#include
int fgetc(FILE *stream);
Description
Gets character from stream, fgetc returns the next character on the named input stream.
Return Value
On success fgetc returns the character read after converting it to an int without sign extension. On end-of-file or error it returns EOF.
Example:
#include
int main(void)
{ FILE *stream;
char string() = "This is a test"; char ch;
/* open a file for update 7
stream = fopenfDUMMY.FIL", "w+");
Fputc()
/* write a string into the file */ fwrite(string, strlen(string), 1, stream);
/* seek to the beginning of the file 7 fseek(stream, 0, SEEK_SET);
do
{ /* read a char from the file */ ch = fgetc(stream);
/* display the character 7
putch(ch); } while (ch != EOF);
fclose(stream); return 0;
}
The fputc() function is functionally similar to the putchar() function, about which we discussed earlier, but it writes a character to a file rather than the standard output.
The syntax is:
#inc!ude
int fputc(int c, FILE *stream);
Description
Puts a character on a stream, fputc outputs character c to the named stream.
Return Value
On success, fputc returns the character c. On error, it returns EOF.
Example:
#include
int main(void)
{ char msg[] = "Hello world";
int i = 0;
while (msg[i])
{ fputc(msg[i], stdout);
i++;
}
return 0; }
The following program illustrates the usage of fgetc() and fputc():
Example:
/* Program to copy input file 'infile' to output file "outfile" */
#include
{
FILE *fin, *fout;
char c;
fin = fopen("infile","r");
fout = fopen("outfile","w");
while((c = fgetc(fin)) != EOF)
fputc(c.fout); fclose(fin); fclose(fout);
}
Formatted Input Output Functions
fscanf()
The fscanf() function is similar to scanf (discussed earlier) as far as the format string and subsequent arguments are concerned. However it contains one additional argument, the first argument, which specifies which file has to be read.
The syntax is:
#include
int fscanf(FILE *stream, const char *format[, address, ...]);
Description
Scans and formats input from a stream, fscanf scans a series of input fields one character at a time reading from a stream. Then each field is formatted according to a format specifier passed to fscanf in the format string pointed to by format. Finally fscanf stores the formatted input at an address passed to it as an argument following format. The number of format specifiers and addresses must be the same as the number of input fields.
fscanf can stop scanning a particular field before it reaches the normal end-of-field character (whitespace) or it can terminate entirely for a number of reasons. See scanf for a discussion of possible causes.
Return Value
fscanf returns the number of input fields successfully scanned, converted and stored. The return value does not include scanned fields that were not stored.
fprintf()
If fscanf attempts to read at end-of-file, the return value is EOF. If no fields were stored, the return value is 0.
Example:
#include
int main(void)
{ inti;
Printf(“lnput an integer: ");
/* read an integer from the
standard input stream */ if (fscanf(stdin, "%d", &i))
printf(“The integer read was: %i\n", i); else
{ fprintf(“stderr, "Error reading an integer from stdinAn");
exit(1);
} return 0;
}
The fprintf() function works similar to the printf() function. It can be used for formatted output to a file.
The syntax is:
#include
int fprintf(FILE *stream, const char *format[, argument, ...]);
Description
Writes formatted output to a stream, fprintf accepts a series of arguments applies to each a format specifier contained in the format string pointed to I format and outputs the formatted data to a stream. There must be the same number of format specifiers as arguments.
Return Value
fprintf returns the number of bytes output. In the event of error it returns EOF.
Example:
#include
int main(void)
{ FILE *stream;
inti = 100; char c = 'C; float f= 1.234;
/* open a file for update */
stream = fopen("DUMMY.FIL", "w+");
/* write some data to the file */ fprintf(stream, "%d %c %f, i, c, f);
/* close the file 7 fclose(stream); return 0;
}
Let us look at another example which writes a floating point number in a file with 10 spaces and two decimal places:
Example:
/*To write a floating point number in a file in 10 spaces, with two decimal places.*/
#include
{
FILE *fp; float fvar; fp = fopen("outfile","w");
fprintf(fp,"%10.2f',fvar);
}
Given below is another program to create a file and write the names entered by the user, into the file.
Example:
#include
{
char name[15];
FILE *fp;
fp = fopen("ofile","w");
printf(“Please enter a name :");
scanf("%s",name);
while(strcmp(name,"xxx") != 0)
{
fprintf(fp,"%s\n",name); printf("Please enter a name :"); scanf("%s",name);
}
fclose(fp); }
Output:
Please enter a name:
Rekha
Please enter a name:
Ritu
Please enter a name:
Please enter a name: xxx
Note:
The names entered like Rekha, Ritu etc. are stored in the file named ofile.
fgets()
The function fgets() can be used to read a complete line of data from a file.
The syntax is:
#include
char *fgets(char *s, int n, FILE *stream);
Description
Gets a string from a stream, fgets reads characters from stream into the string s. The function stops reading when it reads either n -1 characters or a newline character whichever comes first, fgets retains the newline character at the end of s. A null byte is appended to s to mark the end of the string.
Return Value
On success fgets returns the string pointed to by s; it returns NULL on end-of-file or error.
#include
Example:
int main(void)
{ FILE *stream;
char string[] = "This is a test";
char msg[20];
/* open a file for update */
stream = fopen("DUMMY.FIL", "w+");
/* write a string into the file */ fwrite(string, strlen(string), 1, stream);
/* seek to the start of the file */ fseek(stream, 0, SEEK_SET);
/* read a string from the file */ fgets(msg, strlen(string)+1, stream);
/* display the string */
printf("%s", msg);
fclose(stream); return 0; }
fputs()
The fputs() function can be used to write one line of data into a file.
The syntax is:
#include
int fputs(const char *s, FILE *stream);
int fputws(const wchar.t *s, FILE *stream);
Description
Outputs a string on a stream, fputs copies the null-terminated string s to the given output stream; it does not append a newline character and the terminating null character is not copied.
Return Value
On success fputs returns a non-negative value. On error it returns a value of EOF.
Example:
#include
int main(void)
{ /* write a string to standard output 7
fputsf (“Hello world\n", stdout);
return 0; }
Flushing Buffers
The syntax is :
#include
int fflush(FILE 'stream);
Description
Flushes a stream.
If the given stream has buffered output fflush writes the output for stream to the
associated file.
The stream remains open after fflush has executed, fflush has no effect on ar.
unbuffered stream.
Return Value
fflush returns 0 on success. It returns EOF if any errors were detected.
Example.
#include
void flush(FILE *stream);
int main(void)
{ FILE *stream;
char msgfl = "This is a test";
/* create a file */
stream = fopenfDUMMY.FIL", "w");
/* write some data to the file */ fwrite(msg, strlen(msg), 1, stream);
clrscr();
printf("Press any key to flush DUMMY.FIL:");
getch();
/* flush the data to DUMMY.FIL without closing it 7 flush(stream);
printf("\nFile was flushed, Press any key to quit:");
getch();
return 0;
}
void flush(FILE *stream) {
int duphandle;
/* flush the stream's internal buffer */ fflush(stream);
/* make a duplicate file handle */ duphandle = dup(fileno(stream));
/* close the duplicate handle to flush the DOS buffer 7 close(duphandle);
}
Moving Around: Random Access Using fseek()
This function sets the file pointer to the specified position.
The syntax is:
#include
int fseek(FILE *stream, long offset, int whence);
Description
Repositions a file pointer on a stream, fseek sets the file pointer associated with stream to a new position that is offset bytes from the file location given by whence. For text mode streams offset should be 0 or a value returned by ftell. whence must be one of the values 0. 1, or 2 which represent three symbolic constants (defined in stdio.h) as follows:
Constant whence File location
SEEK_SET 0 File beginning
SEEK_CUR 1 Current file pointer position
SEEK_END 2 End-of-file
fseek discards any character pushed back using ungetc. fseek is used with stream I/O; for file handle I/O use Iseek.
After fseek the next operation on an update file can be either input or output.
Return Value
fseek returns 0 if the pointer is successfully moved and nonzero on failure, fseek might return a 0 indicating that the pointer has been moved successfully when in fact it has not been. This is because DOS, which actually resets the pointer, does not verify the setting, fseek returns an error code only on an unopened file or device.
In the event of an error return the global variable errno is set to one of the following values:
EBADF Bad file pointer
EINVAL Invalid argument
ESPIPE Illegal seek on device
Example:
#inc!ude
long filesize(FILE 'stream);
int main(void)
{ FILE *stream;
stream = fopen("MYFILE.TXT", "w+"); fprintf(stream, "This is a test");
printf(“Filesize of MYFILE.TXT is %ld bytes\n", filesize(stream)); fclose(stream); return 0; }
long filesize(FILE *stream)
{ long curpos, length;
curpos = ftell(stream); fseek(stream, 0L, SEEK_END); length = ftell(stream); fseek(stream, curpos, SEEK_SET); return length;
}
Getting Information With feof(), ftell() And ferror() feof()
The function feof() is used to determine whether or not the file pointer is at; end of file position.
The syntax is:
#include
Description
Detects end-of-file on a stream, feof is a macro that tests the given stream for an end-of-file indicator. Once the indicator is set read operations on the return the indicator until rewind is called or the file is closed. The end-of-file indicator is reset with each input operation.
Return Value
feof returns nonzero if an end-of-file indicator was detected on the last input operation on the named stream and 0 if end-of-file has not been reached.
Example:
#include
int main(void)
{ FILE *stream;
/* open a file for reading */ stream = fopen("DUMMY.FIL, "r");
/* read a character from the file */ fgetc(stream);
/* check for EOF */ if (feof(stream)) printf("We have reached end-of-file\n");
/* close the file 7 fclose(stream); return 0; }
ftell() takes a file pointer as argument and returns the current file pointer position.
The syntax is:
#include
long int ftell(FILE 'stream);
Description
Returns the current file pointer, ftell returns the current file pointer for stream. The offset is measured in bytes from the beginning of the file (if the file is binary). The value returned by ftell can be used in a subsequent call to fseek.
Return Value
ftell returns the current file pointer position on success. It returns -1L on error and sets the global variable errno to a positive value.
In the event of an error return the global variable errno is set to one of the following values:
EBADF Bad file pointer
ESPIPE Illegal seek on device
Example:
#include
int main(void)
{ FILE *stream;
stream = fopen("MYFILE.TXT", "w+"); fprintf(stream, "This is a test"); printf("The file pointer is at byte %ld\n", ftell(stream)); fclose(stream); return 0; }
ferror()
The function ferror() is used to check for any input output error.
The syntax is:
#include
int ferror(FILE *stream);
Description
Detects errors on stream, terror is a macro that tests the given stream for a read or write error. If the stream's error indicator has been set it remains set until clearerr or rewind is called or until the stream is closed.
Return Value
terror returns nonzero if an error was detected on the named stream.
Example:
#include
int main(void)
{ FILE *stream; /* open a file for writing */ stream = fopen("DUMMY.FIL", "w"); /* force an error condition by attempting to read */ (void) getc(stream);
if (ferror(stream)) /* test for an error on the stream */
{ /* display an error message */
Printf(“Error reading from DUMMY.FIL\n");
/* reset the error and EOF indicators */
clearerr(stream);
} fclose(stream);
return 0; }
File Handling System Calls
System calls can be used to create files, to provide basic I/O services, to determine file permissions, to change the file permissions etc. A system call is used like any other C user defined or library function. These functions parallel the methods used by MS-DOS to write to the disk. They are more efficient than the C library functions like fopen(),fclose() about which we learnt so far. There is no need to #include any header file in order to use a system call like we used # include
All system calls return the value -1 if they fail.
open()
The open() system call is the first step a process must take to access the data in a file.
int open(pathriame, flag, mode) char *pathname int flag,mode where: pathname is the file-name
flag is
0 for read access
1 for write access
2 read/write access
mode specifies file permissions ( 777 etc.) in case the file is to be created. open() returns an integer called the file descriptor.
read()
The read() system call is used to input data from a file that has been opened in either the read or read/write mode.
int read(file-desc, buffer, num-bytes) int file-desc; char "buffer; int num-bytes;
read() reads num-bytes into buffer from the file with descriptor file-desc.
Example:
int read-bytes, num-bytes = 100;
charstore[100]; intfd;
fd = open("myfile",0);
read-bytes = read(fd,store,num-bytes);
Each call returns a count of the numbers of bytes transferred. A return value of NULL means end of file is encountered. A return value of -1 means error.
Any number of bytes can be read in a call. The most common values are 1, which means one character at a time (unbuffered) and a number like 512,1024 etc. (physical block size).
write()
int write (file-desc,buffer,num) int file-desc, num; char *buffer;
num - number of bytes are transferred from buffer to the file with file-descriptor file-desc.
Write() returns the number of bytes actually transferred.
lseek()
long lseek(fd,offset,origin) intfd, origin; long offset;
Iseek() sets the current position of the file descriptor to offset, relative to location specified by origin in the file whose descriptor is fd.
origin = 0...beginning
1...current position
2...end of file to append to a file, we have to seek to the end before writing
close()
Example:
lseek(fd,NULL,2);
To close an open file we can use this function.
The syntax is:
#include
Description
Closes a file.
The close function closes the file associated with handle, a file handle obtained from a call to creat, creatnew, creattemp, dup, dup2, open, _rtl_creat, or _rtl_open.
It does not write a Ctrl-Z character at the end of the file. If you want to terminate the file with a Ctrl-Z, you must explicitly output one.
Return Value
Upon successful completion, close returns 0.
On error (if it fails because handle is not the handle of a valid, open file), close returns a value of -1 and the global variable errno is set to
EBADF Bad file number
Example:
#include
main()
( int handle;
char buf[11] = "0123456789";
/* create a file containing 10 bytes 7 handle = open("NEW.FIL", 0_CREAT); if(handle>-1)
{ write(handle, buf, strlen(buf));
close(handle); /* close the file */
} else
{ printf(“Error opening file\n");
} return 0;
}
Exercises
1. Write a program to read a file and count the number of characters read.
2. Write a program to read a file and print it in the reverse order.
3. Write a program to input inventory data (item name , number, price and quantity ) from the keyboard and write it into a file, with one record per line.
4. Write a program to store every character typed on the keyboard into a file. The process should continue till the character # is hit from the keyboard.
5. Write a program that will remove all blank lines from a file.
6. Write a program that will remove all comments from a C program file.
Answer to Selected Exercises
3)
#include
main()
{
FILE *f1;
int n.qtyj;
float price; char item[10];
f1 =fopen("data","w");
printf("inventory data\n\n");
printf("item name number price quantity");
for 0=1 ;j<=3;j++)
{
scanf("%s %d %f %d",item,&n,&price,&qty);
fprintf(f1," %s %d %f %d ", item,n,price,qty);
} fclose(f 1);
printf("\n\n");
f1=fopen("data","r");
printf("item name number price quantity");
for 0=1 ;j<=3;j++)
{
fscanf(f1 ,"%s %d %f %d",item,&n,&price,&qty);
printf( "%s %d %f %d ", item,n,price,qty);
} fclose(f 1);
}
4)
# include
# include
{
FILE *f1; char x; clrscr();
f1 =fopen("data","w"); printf("lnput the characters");
while ((x = getc(stdin))!='#')
putc(x,f1);
fclose(f 1);
f1=fopen("data","r");
printf("The input characters are\n ");
while ((x = getc(f1))!=EOF)
putchar(x);
getch();
fclose(f 1); }