0% found this document useful (0 votes)
94 views9 pages

8 File

Files in C are treated as a series of bytes that can be accessed sequentially. To manipulate a file, a stream must be associated with it using routines in the standard library like fopen(). Streams buffer input and output to improve performance by avoiding waiting for slow devices. When opening a file, the access mode like read, write, or append must be specified. It's important to check for errors by validating file operations don't return NULL and using perror() to print error messages.

Uploaded by

ajaykaundal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views9 pages

8 File

Files in C are treated as a series of bytes that can be accessed sequentially. To manipulate a file, a stream must be associated with it using routines in the standard library like fopen(). Streams buffer input and output to improve performance by avoiding waiting for slow devices. When opening a file, the access mode like read, write, or append must be specified. It's important to check for errors by validating file operations don't return NULL and using perror() to print error messages.

Uploaded by

ajaykaundal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

File

A file is a collection of related data. C treats a file as a series of bytes.


The standard library
C uses routines in the Standard Library; because they are covered by the Standard will always work the same way despite the
environment they are used in. Opening a file is rather like being presented with a large array of characters, except whereas an array
provides random access to its elements a file provides sequential access to its characters. It is possible to achieve random access, but
the routines are most easily driven forwards through the file character by character
Streams
The procedure by which files are manipulated in c is that a stream must be associated with a file to be read or written, A stream is a
black box in that you dont rally need to know what is going on in a stream.

Whenever a C program runs it has 3 streams associated with it these are


1. the standard input or stdin connected to the keyboard . When characters are read form stdin the program will wait for the
user to type something. Scanf for instance uses stdin
2. the standard output or stdout , connected to the screen . When characters are written to stdout characters appear on the
screen printf for instance uses stdout.
3. the standard error, or stderr also connected to the screen, Characters written to stderr will also appear on the screen . The
perror function uses stderr.

What is Stream ?
Stream must be associated with each file to be manipulated.
Stream were invented in very early days of C when devices were slow . Programs executing in memory run much faster then
hardware devices can provide the information they need. It was found that when a program read characters individually form a
disk , the program would have to wait excessively for the correct part of the disk , the program would have to wait excessively for
the correct part of the disk to spin around. The character would be grabbed and processed then the program would have to wait
again for the disk.
Caches
In the intervening years manufacturers have invented caches so the disk never reads a single character. Thus when the program
requests the next character it is provided immediately from the buffer. Complex alogorithms are used to determine which character
should be buffered and which should be discarded.
Streams do this buffering in software. Thus if the device you are using does not support caching, it doesnt matter because the
stream will do it for you.

Text Streams

A text stream transports the characters of a text that is divided into lines. A line of text consists of a sequence of characters ending in
a newline character. A line of text can also be empty, meaning that it consists of a newline character only. The last line transported
may or may not have to end with a newline character, depending on the implementation.

Binary Streams

A binary stream is a sequence of bytes that are transmitted without modification. In other words, the I/O functions do not involve
any interpretation of control characters when operating on binary streams . Data written to a file through a binary stream can always
be read back unchanged on the same system. However, in certain implementations there may be additional zero-valued bytes
appended at the end of the stream.

Stdin is Line Buffered


/*characters typed at the keyboard are buffered until Enter is pressed*/
#include <stdio.h> }
#include <conio.h> ajay
void main () read a
{ read j
int ch; read a
clrscr(); read y
while ((ch=getchar())!=EOF) read
printf("Read '%c'\n",ch) ;
printf("EOF\n"); ^Z
getch(); EOF
Program uses the getchar routine. The importand thing to notice is that because getchar uses the stdin stream and stdin is line
buffered, the character ajay which are typed are not processed until the enter key is pressed. Then they are processed in one go as
the loop executes four times.
Under MS-DOS the control Z character is used to indicate end of file. When this is typed the getchar routine returns EOF and the
loop terminates.

Whether char is signed or unsigned. This seems rather irrelevant until it is revealed that the value of the EOF is 1. Now if a
compiler chose to implement char as an unsigned quantity when getchar returned 1 to indicate end of file , it would casues 255 to
be stored. When the 255 were compared with the 1 value of EOF the comparison would fail

Opening Files
Opening and Closing Files
To write to a new file or modify the contents of an existing file, you must first open the file. When you open a file, you must specify
an access mode indicating whether you plan to read, to write, or some combination of the two. When you have finished using a file,
close it to release resources.
Access Modes
The access mode specified by the second argument to fopen( ) or freopen( ) determines what input and output operations
the new stream permits. The permissible values of the mode string are restricted.
The first character in the mode string is always r for "read," w for "write," or a for "append," and in the simplest case, the string
contains just that one character. However, the mode string may also contain one or both of the characters + and b (in either order:
+b has the same effect as b+).
A plus sign (+) in the mode string means that both read and write operations are permitted. However, a program must not alternate
immediately between reading and writing. After a write operation, you must call the fflush( ) function or a positioning function
(fseek( ), fsetpos( ), or rewind( )) before performing a read operation. After a read operation, you must call a
positioning function before performing a write operation.
A b in the mode string causes the file to be opened in binary mode that is, the new stream associated with the file is a binary stream.
If there is no b in the mode string, the new stream is a text stream.
If the mode string begins with r, the file must already exist in the file system.
If the mode string begins with w, then the file will be created if it does not already exist. If it does exist, its previous contents will be
lost, because the fopen( ) function truncates it to zero length in "write" mode.
A mode string beginning with a (for append) also causes the file to be created if it does not already exist. If the file does exist,
however, its contents are preserved, because all write operations are automatically performed at the end of the file. Here is a brief
example:
Closing file
The function flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the stream's
input and output buffers. The fclose( ) function returns zero on success, or EOF if an error occurs.
When the program exits, all open files are closed automatically. Nonetheless, you should always close any file that you have
finished processing. Otherwise, you risk losing data in the case of an abnormal program termination.

Files are opened and streams created with the fopen function.
Before a file may be manipulated a stream must be associated with it. This association between stream and file is made with the
fopen routine.
All that is needed is to plug in the file name, the access mode(read, write, append) and the stream comes back..
A stream is actually declared as FILE * i.e. a pointer to a FILE structure.

Dealing with Errors


fopen may fail for one of many reasons , how to tell which?
#include <stdio.h> {
#include <conio.h> fprintf(stderr,"open of file failed ");
void main () perror("because");
{ }
FILE* in; getch();
clrscr(); }
if((in=fopen("alo.txt","r"))==NULL)
The important thing to realize about streams is that because they are pointer it is possible for fopen to indicate a problem by
returning NULL. This is a special definition of an invalid pointer seen previously. Thus if fopen returns NULL, we are guaranteed
something has gone wrong.

What Went Wrong?


The Standard library deals with errors by manipulating a variable called errno, the error number, Each implementation of C
assigns a unique number to each possible error situation. Thus 1 could be file does not exit and so on. It is possible to access
errno by placing
Extern int errno;
Fprintf(open of file failed because %i,errno);
This would produce:
Opend of file failed because 1
Which is rather unhelpful . What perror does is to look up the value of 1 in a table and find a useful text message,

Formatted File Input and Output

Formatted file input/output deals with text and numeric data that is formatted in a specific way.

Displaying a File
#include <stdio.h> if((in_stream=fopen(in_name,"r"))==NULL)
#include <conio.h> {
void main() fprintf(stderr,"open of %s for reading failed",in_name);
{ perror(" because ");
char in_name[80]; }
FILE *in_stream; while((ch=fgetc(in_stream))!=EOF)
int ch; putchar(ch);
clrscr(); fclose(in_stream);
printf("Display file : "); getch();
scanf("%79s",in_name); }

make a text file in c drive give full address for example c:\as.txt

%79 prevent the user from corrupting memory if more than 79 characters are typed.

/* Demonstrates the fprintf() function. */


#include <stdlib.h>
#include <stdio.h> clear_kb();
#include <conio.h>
puts("Enter a name for the file.");
void clear_kb(void); gets(filename);

void main() if ( (fp = fopen(filename, "w")) == NULL)


{ {
FILE *fp; fprintf(stderr, "Error opening file %s.", filename);
float data[5]; exit(1);
int count; }
char filename[20]; /* Write the numerical data to the file and to stdout. */
clrscr();
for (count = 0; count < 5; count++)
puts("Enter 5 floating-point numerical values."); {
fprintf(fp, "\ndata[%d] = %f", count, data[count]);
for (count = 0; count < 5; count++) fprintf(stdout, "\ndata[%d] = %f", count, data[count]);
scanf("%f", &data[count]); }
fclose(fp);
/* Get the filename and open the file. First clear stdin */ printf("\n");
/* of any extra characters. */ //return(0);
getch(); {
} char junk[80];
gets(junk);
void clear_kb(void) }
/* Clears stdin of any waiting characters. */

Character Input and Output


When used with disk files, the term character I/O refers to single characters as well as lines of characters. Remember, a line is a
sequence of zero or more characters terminated by the newline character. Use character I/O with text-mode files. The following
sections describe character input/output functions, and then you'll see a demonstration program.
Int fgetc(FILE* stream);
Read individual character form a file.
The fgets() Function
To read a line of characters from a file, use the fgets() library function. The prototype is
char *fgets(char *str, int n, FILE *fp);
The argument str is a pointer to a buffer in which the input is to be stored, n is the maximum number of characters to be input, and
fp is the pointer to type FILE that was returned by fopen() when the file was opened.
When called, fgets() reads characters from fp into memory, starting at the location pointed to by str. Characters are read until a
newline is encountered or until n-1 characters have been read, whichever occurs first
Character Output
You need to know about two character output functions: putc() and fputs().
The putc() Function
The library function putc() writes a single character to a specified stream. Its prototype in STDIO.H reads
int putc(int ch, FILE *fp);
The argument ch is the character to output. As with other character functions, it is formally called a type int, but only the lower-
order byte is used. The argument fp is the pointer associated with the file (the pointer returned by fopen() when the file was opened).
The function putc() returns the character just written if successful or EOF if an error occurs. The symbolic constant EOF is defined
in STDIO.H, and it has the value -1. Because no "real" character has that numeric value, EOF can be used as an error indicator (with
text-mode files only).
The fputs() Function
To write a line of characters to a stream, use the library function fputs(). This function works just like puts(), covered on Day 14.
The only difference is that with fputs() you can specify the output stream. Also, fputs() doesn't add a newline to the end of the string;
if you want it, you must explicitly include it. Its prototype in STDIO.H is
char fputs(char *str, FILE *fp);
The argument str is a pointer to the null-terminated string to be written, and fp is the pointer to type FILE returned by fopen() when
the file was opened. The string pointed to by str is written to the file, minus its terminating \0. The function fputs() returns a
nonnegative value if successful or EOF on error.
Binary files

Fopen wb:- wb opeion puts the steam into binary write mode
Direct File Input and Output
Direct I/O is used only with binary-mode files. With direct output, blocks of data are written from memory to disk. Direct input
reverses the process: A block of data is read from a disk file into memory. For example, a single direct-output function call can write
an entire array of type double to disk, and a single direct-input function call can read the entire array from disk back into memory.
The direct I/O functions are fread() and fwrite().
The fwrite() Function
The fwrite() library function writes a block of data from memory to a binary-mode file. Its prototype in STDIO.H is
int fwrite(void *buf, int size, int count, FILE *fp);
The argument buf is a pointer to the region of memory holding the data to be written to the file. The pointer type is void; it can be a
pointer to anything.
The argument size specifies the size, in bytes, of the individual data items, and count specifies the number of items to be written. For
example, if you wanted to save a 100-element integer array, size would be 2 (because each int occupies 2 bytes) and count would be
100 (because the array contains 100 elements). To obtain the size argument, you can use the sizeof() operator.
The argument fp is, of course, the pointer to type FILE, returned by fopen() when the file was opened. The fwrite() function returns
the number of items written on success; if the value returned is less than count, it means that an error has occurred. To check for
errors, you usually program fwrite() as follows:
if( (fwrite(buf, size, count, fp)) != count)
fprintf(stderr, "Error writing to file.");
Here are some examples of using fwrite(). To write a single type double variable x to a file, use the following:
fwrite(&x, sizeof(double), 1, fp);
To write an array data[] of 50 structures of type address to a file, you have two choices:
fwrite(data, sizeof(address), 50, fp);
fwrite(data, sizeof(data), 1, fp);
The first method writes the array as 50 elements, with each element having the size of a single type address structure. The second
method treats the array as a single element. The two methods accomplish exactly the same thing.
The following section explains fread() and then presents a program demonstrating fread() and fwrite().
The fread() Function
The fread() library function reads a block of data from a binary-mode file into memory. Its prototype in STDIO.H is
int fread(void *buf, int size, int count, FILE *fp);
The argument buf is a pointer to the region of memory that receives the data read from the file. As with fwrite(), the pointer type is
void.
The argument size specifies the size, in bytes, of the individual data items being read, and count specifies the number of items to
read. Note how these arguments parallel the arguments used by fwrite(). Again, the sizeof() operator is typically used to provide the
size argu-ment. The argument fp is (as always) the pointer to type FILE that was returned by fopen() when the file was opened. The
fread() function returns the number of items read; this can be less than count if end-of-file was reached or an error occurred.

Sequential Versus Random File Access


The ftell() and rewind() Functions
To set the position indicator to the beginning of the file, use the library function rewind(). Its prototype, in STDIO.H, is
void rewind(FILE *fp);
The argument fp is the FILE pointer associated with the stream. After rewind() is called, the file's position indicator is set to the
beginning of the file (byte 0). Use rewind() if you've read some data from a file and you want to start reading from the beginning of
the file again without closing and reopening the file.
To determine the value of a file's position indicator, use ftell(). This function's prototype, located in STDIO.H, reads
long ftell(FILE *fp);
The argument fp is the FILE pointer returned by fopen() when the file was opened. The function ftell() returns a type long that gives
the current file position in bytes from the start of the file (the first byte is at position 0). If an error occurs, ftell() returns -1L (a type
long -1).
/* Demonstrates ftell() and rewind(). */ {
#include <stdlib.h> fprintf(stderr, "Error opening file.");
#include <stdio.h> exit(1);
#include <conio.h> }
printf("\nImmediately after opening, position = %ld",
#define BUFLEN 6 ftell(fp));

char msg[] = "abcdefghijklmnopqrstuvwxyz"; /* Read in 5 characters. */


fgets(buf, BUFLEN, fp);
main() printf("\nAfter reading in %s, position = %ld", buf,
{ ftell(fp));
FILE *fp;
char buf[BUFLEN]; /* Read in the next 5 characters. */
clrscr();
if ( (fp = fopen("TEXT.TXT", "w")) == NULL) fgets(buf, BUFLEN, fp);
{ printf("\n\nThe next 5 characters are %s, and position now
fprintf(stderr, "Error opening file."); = %ld",
exit(1); buf, ftell(fp));
} /* Rewind the stream. */
rewind(fp);
if (fputs(msg, fp) == EOF) printf("\n\nAfter rewinding, the position is back at %ld",
{ ftell(fp));
fprintf(stderr, "Error writing to file.");
exit(1); /* Read in 5 characters. */
} fgets(buf, BUFLEN, fp);
printf("\nand reading starts at the beginning again: %s\n",
fclose(fp); buf);
fclose(fp);
/* Now open the file for reading. */ getch();
if ( (fp = fopen("TEXT.TXT", "r")) == NULL) }
The fseek() Function
More precise control over a stream's position indicator is possible with the fseek() library function. By using fseek(), you can set the
position indicator anywhere in the file. The function prototype, in STDIO.H, is
int fseek(FILE *fp, long offset, int origin);
The argument fp is the FILE pointer associated with the file. The distance that the position indicator is to be moved is given by
offset in bytes. The argument origin specifies the move's relative starting point. There can be three values for origin, with symbolic
constants defined in IO.H, as shown in Table 16.2.
Possible origin values for fseek().
Constant Value Description
SEEK_SET 0 Moves the indicator offset bytes from the beginning of the file.
SEEK_CUR 1 Moves the indicator offset bytes from its current position.
SEEK_END 2 Moves the indicator offset bytes from the end of the file.
The function fseek() returns 0 if the indicator was successfully moved or nonzero if an error occurred
/* Random access with fseek(). */

#include <stdlib.h> break;


#include <stdio.h> else if (offset > MAX-1)
#include <conio.h> continue;
#define MAX 50
main() /* Move the position indicator to the specified element.
{ */
FILE *fp;
int data, count, array[MAX]; if ( (fseek(fp, (offset*sizeof(int)), SEEK_SET)) != 0)
long offset; {
clrscr(); fprintf(stderr, "\nError using fseek().");
/* Initialize the array. */ exit(1);
for (count = 0; count < MAX; count++) }
array[count] = count * 10;
/* Open a binary file for writing. */ /* Read in a single integer. */

if ( (fp = fopen("RANDOM.DAT", "wb")) == NULL) fread(&data, sizeof(int), 1, fp);


{
fprintf(stderr, "\nError opening file."); printf("\nElement %ld has value %d.", offset, data);
exit(1); }
}
/* Write the array to the file, then close it. */ fclose(fp);
if ( (fwrite(array, sizeof(int), MAX, fp)) != MAX) getch();
{ }
fprintf(stderr, "\nError writing data to file.");
} Enter element to read, 0-49, -1 to quit:
fclose(fp); 5
/* Open the file for reading. */ Element 5 has value 50.
if ( (fp = fopen("RANDOM.DAT", "rb")) == NULL) Enter element to read, 0-49, -1 to quit:
{ 6
fprintf(stderr, "\nError opening file."); Element 6 has value 60.
} Enter element to read, 0-49, -1 to quit:
49
/* Ask user which element to read. Input the element */ Element 49 has value 490.
/* and display it, quitting when -1 is entered. */ Enter element to read, 0-49, -1 to quit:
while (1) 1
{ Element 1 has value 10.
printf("\nEnter element to read, 0-%d, -1 to quit: Enter element to read, 0-49, -1 to quit:
",MAX-1); 0
scanf("%ld", &offset); Element 0 has value 0.
if (offset < 0) -1
Deleting a File
To delete a file, you use the library function remove(). Its prototype is in STDIO.H, as follows:
int remove( const char *filename );
The variable *filename is a pointer to the name of the file to be deleted. (See the section on filenames earlier in this chapter.) The
specified file must not be open. If the file exists, it is deleted (just as if you used the DEL command from the DOS prompt or the rm
command in UNIX), and remove() returns 0. If the file doesn't exist, if it's read-only, if you don't have sufficient access rights, or if
some other error occurs, remove() returns -1.
/* Demonstrates the remove() function. */ gets(filename);
#include <stdio.h>
#include <conio.h> if ( remove(filename) == 0)
void main() printf("The file %s has been deleted.\n", filename);
{ else
char filename[80]; fprintf(stderr, "Error deleting the file %s.\n", filename);
clrscr(); getch();
printf("Enter the filename to delete: "); }

Renaming a File
The rename() function changes the name of an existing disk file. The function prototype, in STDIO.H, is as follows:
int rename( const char *oldname, const char *newname );
The filenames pointed to by oldname and newname follow the rules given earlier in this chapter. The only restriction is that both
names must refer to the same disk drive; you can't rename a file to a different disk drive. The function rename() returns 0 on
success, or -1 if an error occurs. Errors can be caused by the following conditions (among others):
The file oldname does not exist.
A file with the name newname already exists.
You try to rename to another disk.
/* Using rename() to change a filename. */
#include <stdio.h> gets(newname);
#include <conio.h>
if ( rename( oldname, newname ) == 0 )
main() printf("%s has been renamed %s.\n", oldname,
{ newname);
char oldname[80], newname[80]; else
clrscr(); fprintf(stderr, "An error has occurred renaming %s.\n",
printf("Enter current filename: "); oldname);
gets(oldname); getch();
printf("Enter new name for file: ");
}

Coping file
#include <stdio.h> }
#include <conio.h> printf("Destination file : ");scanf("%79s",out_name);
void main() if((out_stream=fopen(out_name,"w"))==NULL)
{ {
char in_name[80],out_name[80]; fprintf(stderr,"open of %s for reading failed",out_name);
FILE *in_stream,*out_stream; perror(" because");
int ch; }
clrscr(); while ((ch=fgetc(in_stream))!=EOF)
printf("source file : ");scanf("%79s",in_name); fputc(ch,out_stream);
if((in_stream=fopen(in_name,"r"))==NULL) fclose(in_stream);
{ fclose(out_stream);
fprintf(stderr,"open of %s for reading failed",out_name); getch();
perror(" because"); }

/*writes stings from keyword and saves it in file*/


#include<stdio.h> char s[80];
#include<conio.h> clrscr();
main() fp=fopen("ajay.txt","w");
{ printf("Enter a line of text= ");
FILE *fp; while(strlen(gets(s))>0)
{ fclose(fp);
fputs(s,fp); getch();
fputs("\n",fp); }
}

/*REad string from file and display on screen*/


#include<stdio.h> fp=fopen("ajay.txt","r");
#include<conio.h> while(fgets(c,79,fp)!=NULL)
main() printf("%s",c);
{ fclose(fp);
FILE *fp; getch();
char c[80]; }
clrscr();

/*Let us C count chars spaces tab and new line in fileprogram perform file I/O in high level unformatted text mode*/
#include<stdio.h> noc++;
#include<conio.h> if(ch==' ')
#define N 4 nob++;
main() if(ch=='\n')
{ nol++;
FILE *fp; if(ch=='\t')
char ch; not++;
int nol=0,not=0,nob=0,noc=0; }
clrscr(); fclose(fp);
fp=fopen("ajay.txt","r"); printf("\nCharacter=%d",noc-nol);
while(1) printf("\nBlank=%d",nob);
{ printf("\nTabs=%d",not);
ch=getc(fp); printf("\nLines=%d",nol);
if(ch==EOF) getch();
break; }

/***/
#include<stdio.h> fp=fopen(fname,"r");
#include<conio.h> while(1)
#include<string.h> {
void main() c=fgetc(fp);
{ if(c==EOF)
FILE *fp; break;
char fname[13]; i= ftell(fp);
char ext[5]=".txt";
char c; }
int i=0,a; fclose(fp);
printf("Enter file name="); printf("Total byte in file = %d\n",i);
gets(fname); getch();
}
strcat(fname,ext);

/*write a program to create a file open it type in some character and count the number of character in file*/
#include<stdio.h> while(strlen(gets(c))>0)
#include<conio.h> {
main() fputs(c,fp);
{ fputs("\n",fp);
FILE *fp,*an; }
int i,count=0; fclose(fp);
char x,c[100]; //open file again to enter text and count number of character
//clrscr(); fp=fopen("new.txt","r");
fp=fopen("new.txt","w");//file has been opened in text mode while(1)
that why Dos will count enter a character {
printf("Enter a any character="); x=fgetc(fp);
if(x==EOF) printf("Number of character you have entered is
break; %d",count);
count++; getch();
} }
fclose(fp);
/*write a program tht will input a person first name, last name, SSB number and age and write the information to a data
file. One person's information should be in a single line. Use the function fprintf to write to the data file. Accept the
information and write the data within a loop. Your program should exit the loop when the word 'EXIT' is entered for the
first name. Remember to close the file termination the program. Use the function strcmp() to compare two strings.*/
#include<conio.h>
#include<stdio.h>
#include<process.h>
#include<string.h>
void main()
{
struct emp{
char name[10],last[10];
int ssn,age;
}e[2];
int i;
char x[4]="EXIT";
FILE *fp;
fp=fopen("emp.txt","w");
for(i=0;i<2;i++)
{
printf("Enter EXIT in field name to exit\n");
printf("enter data name,last name, ssn ,age\n");

scanf("%s %s %d
%d",&e[i].name,&e[i].last,&e[i].ssn,&e[i].age);
if(stricmp(x,e[i].name)==0)
exit(0);
else
fwrite(e,sizeof(struct emp),2,fp);
}
fclose(fp);

You might also like