You are on page 1of 19

C File Processing

The Data hierarchy


 The smallest piece of information in computer is the bit(binary digit) which
is 0 or 1.
 Human being deals with alphabets and numbers (1, 2, 3, ..,a, b, c..). Every
character can be represented by 8 bits or a byte.
 Fields are composed of characters(bytes), Example:
 Firstname is a field contains value “Mona” which is 4 bytes or 32bits.
 Structure in C is composed of several fields, example:
 Struct Employee{
 char fname[10];
 char lname[10];
 char ssn[10];
 int age;
 char passw[10];
 }

10/29/20 prog II - C / C++ 2


The Data hierarchy
(continued)
 A file is group of structure records.
 To facilitate the retrieval of specific records from a file, we need a
record key.
 Many ways to organize records in file:
 Sequential access-file: records stored in order by record key field.
 Random-access file:records are accessed directly without searching thru
other records.
 A group of related files is called database

10/29/20 prog II - C / C++ 3


File Declaration
 You declare a variable fp to store a file pointer like this:
 FILE *fp;
 The type FILE is predefined for you by <stdio.h>. It is a data
structure which holds the information the standard I/O library
needs to keep track of the file for you.
 If you were reading from two files at once you'd probably use
two file pointers:
 FILE *fp1, *fp2;
 If you were reading from one file and writing to another you
might declare an input file pointer and an output file pointer:
 FILE *ifp, *ofp;

10/29/20 prog II - C / C++ 4


Access Modes
 "r" read
 "w" write (destroys any existing file with the same
name)
 “a” append; open or create a file for writing at end of
file.
 "rb" read a binary file
 "wb" write a binary file (overwriting any existing file)
 "r+" opens an existing file for random read access, and
writing to its end (for update)
 "w+" Create a new file for random read access, and
writing to its end (destroys any existing file with the
same name) – for update.

10/29/20 prog II - C / C++ 5


Initializing File pointer
 Like any pointer variable, a file pointer isn't any good
until it's initialized to point to something.
 To open the file input.dat for reading you might call:
 ifp = fopen("input.dat", "r");
 The mode string "r" indicates reading.
 Mode "w" indicates writing, so we could open
output.dat for output like this:
 ofp = fopen("output.dat", "w");

10/29/20 prog II - C / C++ 6


fopen
 One thing to beware of when opening files is that it's an
operation which may fail. The requested file might not exist, or
it might be protected against reading or writing.
 fopen returns a null pointer if it can't open the requested file.
Every call to fopen will typically be followed with a test, like this:
 ifp = fopen("input.dat", "r");

 if(ifp == NULL) {
 printf("can't open file\n");

 exit or return }
 It's common to collapse the call to fopen and the assignment in
with the test:
 if((ifp = fopen("input.dat", "r")) == NULL) {
 printf("can't open file\n");
 exit or return }

10/29/20 prog II - C / C++ 7


Predefined Streams

 Besides the file pointers which we explicitly open by calling


fopen, there are also three predefined streams.
 stdin is a constant file pointer corresponding to standard input.
 stdout is a constant file pointer orresponding to standard
output.
 Stderr: standard error, like stdout, stderr is typically connected
to the screen by default.
 Stdin and stdout can be used anywhere a file pointer is called
for; for example:
 getchar() is the same as getc(stdin)
 putchar(c) is the same as putc(c, stdout).

10/29/20 prog II - C / C++ 8


FILE Functions
 Once the file is opened, you can use the following functions
to read/write it:
 int getc (FILE *fp) Returns the next character from `fp', or EOF on
error or end-of-file.
 int putc (int c, FILE *fp) Write the character c to the file `fp',
returning the character written, or EOF on error.
 int fscanf (FILE *fp, char *format, ...) Like scanf, except input is
taken from the file fp.
 int fprintf (FILE *fp, char *format, ...) Like printf, except output is
written to the file fp.
 char *fgets (char *line, int n, FILE *fp) Gets the next line of input
from the file fp, up to `n-1' characters in length. The newline
character is included at the end of the string, and a null is appended.
Returns `line' if successful, else NULL if end-of-file or other error.
 int fputs (char *line, FILE *fp) Outputs the string `line' to the file
fp. Returns zero is successful, EOF if not.

10/29/20 prog II - C / C++ 9


More FILE Functions
 int fclose (FILE *fp) Closes the file 'fp', after flushing any buffers.

 int fflush (FILE *fp) Flushes any buffers associated with the file
'fp'.
 To check the status of a file, the following functions can be
called:
 int feof (FILE *fp) Returns non-zero when an end-of-file is read.
 int ferror (FILE *fp) Returns non-zero when an error has
occurred, unless cleared by clearerr.
 void clearerr (FILE *fp) Resets the error and end-of-file statuses.
 int fileno (FILE *fp) Returns the integer file descriptor associated
with the file (useful for low-level I/O).

10/29/20 prog II - C / C++ 10


Sequential write example
#include <stdio.h>
main()
{
int account;
char name[30];
double balance;
FILE *cfptr;
if((cfptr=fopen("clients.dat","w"))==NULL)
printf("\nfile could not be opened\n");
else {
printf("Enter account, Name,and balance\n");
printf("Enter EOF CTRL^Z to end input\n");
printf("?");
scanf("%d%s%lf",&account,name,&balance);
while (!feof(stdin)){
fprintf(cfptr,"%d %s %.2f\n",account,name,balance);
printf("?");
scanf("%d%s%lf",&account,name,&balance);}

fclose(cfptr); } }

10/29/20 prog II - C / C++ 11


Sequential read example
#include <stdio.h>
main()
{
int account;
char name[30];
double balance;
FILE *cfptr;
if((cfptr=fopen("clients.dat","r"))==NULL)
printf("\nfile could not be opened\n");
else {
printf("%-10s%-13s%s\n","Account","Name","Balance\n");
fscanf(cfptr,"%d %s %lf",&account,name,&balance);
while (!feof(cfptr)){
printf("%-10d%-13s%7.2f\n",account,name,balance);
fscanf(cfptr,"%d %s %lf",&account,name,&balance);
}
fclose(cfptr);
}
}

10/29/20 prog II - C / C++ 12


Random-access files
 Records in a sequential file created with
the formatted output function “fprintf”
are not necessarily the same length.
 Records in Random accessed files are
normally fixed in length and may be
accessed directly.
record
0 100 200 300

100 bytes 100 bytes 100 bytes 100 bytes


Random-accessed file w/ 4 records

10/29/20 prog II - C / C++ 13


Random-access files Functions
 fwrite(arg1,arg2,arg3,arg4)
 arg1: address of element to write
 arg2: size of element(in bytes) to write
 arg3: number of elements to write.
 arg4: file to write into
 fread(arg1,arg2,arg3,arg4)
 arg1: address of element to read
 arg2: size of element(in bytes) to read
 arg3: number of elements to read.
 arg4: file to read from
 Fseek(arg1,arg2,arg3)
 Arg1: file to seek
 Arg2: offset, displacement or position in file to seek
 Arg3:
 SEEK_SET: seek starts at beginning of file
 SEEK_CUR:seek starts at current position
 SEEK_END:seek starts at end of file

10/29/20 prog II - C / C++ 14


Random-Access Example (Blank file)
#include <stdio.h>
struct clientdata{
int accnum;
char lastname[15];
char firstname[10];
double balance;
};
main() {
int i;
struct clientdata blankclient={0,"","",0.0};
FILE *cfptr;
if ((cfptr=fopen("credit.dat","w"))==NULL)
printf("file could not be opened.\n");
else {
for (i=1;i<=100;i++)
fwrite(&blankclient,sizeof(struct clientdata),1,cfptr);
fclose(cfptr);
}
}

10/29/20 prog II - C / C++ 15


Random Access file (fwrite)
#include <stdio.h>
struct clientdata{
int accnum;
char lastname[15];
char firstname[10];
double balance;
};
main(){
int i;
struct clientdata client={0,"","",0.0};
FILE *cfptr;
if ((cfptr=fopen("credit.dat","r+"))==NULL)
printf("file could not be opened.\n");
else {
printf("enter account number(1-100) 0 to end\n");
scanf("%d",&client.accnum);
while (client.accnum !=0) {
printf("enter lastname, firstname, balance\n");
fscanf(stdin,"%s%s%lf",client.lastname,client.firstname,&client.balance);
fseek(cfptr,(client.accnum-1)*sizeof(struct clientdata),SEEK_SET);
fwrite(&client,sizeof(struct clientdata),1,cfptr);
printf("enter account number(1-100) 0 to end\n");
scanf("%d",&client.accnum);}
fclose(cfptr);
}
}

10/29/20 prog II - C / C++ 16


Random Access file (fread)
#include <stdio.h>
struct clientdata{
int accnum;
char lastname[15];
char firstname[10];
double balance;
};
main(){
int i;
struct clientdata client={0,"","",0.0};
FILE *cfptr;
if ((cfptr=fopen("credit.dat","r"))==NULL)
printf("file could not be opened.\n");
else {
printf("%-6s%-16s%-11s%10s\n","Acct","Last Name","First Name","Balance");
while (!feof(cfptr)) {
fread(&client,sizeof(struct clientdata),1,cfptr);
if (client.accnum !=0)
printf("%-6d%-16s%-11s
%10.2f\n",client.accnum,client.lastname,client.firstname,client.balance);
}
fclose(cfptr);
}
}

10/29/20 prog II - C / C++ 17


Deleting a File

To delete a file : remove()


Its prototype in stdio.h as
int remove(const char *filename)
If the file exists, it is deleted and remove() return 0.
If the file does not exist,
If it’s read-only,
If some other error occurs,
remove() returns -1

10/29/20 prog II - C / C++ 18


Rename a File

To rename a file : rename()


Its prototype in stdio.h as
int rename(const char *oldname, const char *newname)
Restriction is that both names must refer to the same disk drives
Rename() return 0 on success,
Rename() return 1 if error occurs.

10/29/20 prog II - C / C++ 19

You might also like