0% found this document useful (0 votes)
7 views

L21 Fileinputoutput

Uploaded by

lacrosseman1214
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

L21 Fileinputoutput

Uploaded by

lacrosseman1214
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Introduction

• Data files
– Can be created, updated, and processed by C
programs
– Are used for permanent storage of large
amounts of data
• Storage of data in variables and arrays is only
temporary
The Data Hierarchy
• Data Hierarchy:
– Bit – smallest data item
• Value of 0 or 1
– Byte – 8 bits
• Used to store a character
– Decimal digits, letters, and special symbols
– Field – group of characters conveying meaning
• Example: your name
– Record – group of related fields
• Represented by a struct or a class
• Example: In a payroll system, a record for a particular
employee that contained his/her identification number, name,
address, etc.
The Data Hierarchy
• Data Hierarchy (continued):
– File – group of related records
• Example: payroll file
– Database – group of related files
Sally Black
Tom Blue
Judy Green File
Iris Orange
Randy Red

Judy Green Record


Judy Field
01001010 Byte (ASCII character J)

1 Bit
The Data Hierarchy
• Data files
– Record key
• Identifies a record to facilitate the retrieval of
specific records from a file
– Sequential file
• Records typically sorted by key
Files and Streams
• C views each file as a sequence of bytes
– File ends with the end-of-file marker
• Or, file ends at a specified byte
• Stream created when a file is opened
– Provide communication channel between files and
programs
– Opening a file returns a pointer to a FILE
structure
• Example file pointers:
• stdin - standard input (keyboard)
• stdout - standard output (screen)
• stderr - standard error (screen)
Files and Streams
• Read/Write functions in standard library
– fgetc
• Reads one character from a file
• Takes a FILE pointer as an argument
• fgetc( stdin ) equivalent to getchar()
– fputc
• Writes one character to a file
• Takes a FILE pointer and a character to write as an argument
• fputc( 'a', stdout ) equivalent to putchar( 'a' )
– fgets
• Reads a line from a file
– fputs
• Writes a line to a file
– fscanf / fprintf
• File processing equivalents of scanf and printf
Creating a Sequential Access File
• C imposes no file structure
– No notion of records in a file
– Programmer must provide file structure
• Creating a File
– FILE *myPtr;
• Creates a FILE pointer called myPtr
– myPtr = fopen("myFile.dat",
openmode);
• Function fopen returns a FILE pointer to file specified
• Takes two arguments – file to open and file open mode
• If open fails, NULL returned
– fprintf
• Used to print to a file
• Like printf, except first argument is a FILE pointer (pointer to
the file you want to print in)
Creating a Sequential Access
File
– feof( FILE pointer )
• Returns true if end-of-file indicator (no more data to process) is
set for the specified file
– fclose( FILE pointer )
• Closes specified file
• Performed automatically when program ends
• Good practice to close files explicitly
• Details
– Programs may process no files, one file, or many files
– Each file must have a unique name and should have its
own pointer
Creating a Sequential Access
File

• Table of file open modes:


Mod e Desc rip tion
r Open a file for reading.
w Create a file for writing. If the file already exists,
discard the current contents.
a Append; open or create a file for writing at end of file.
r+ Open a file for update (reading and writing).
w+ Create a file for update. If the file already exists,
discard the current contents.
a+ Append; open or create a file for update; writing is
done at the end of the file.
1
2
3
Create a sequential file */
#include <stdio.h>
1. Initialize
4
5 int main()
variables and
6
7
{
int account;
FILE pointer
8 char name[ 30 ];
9
10
double balance;
FILE *cfPtr; /* cfPtr = clients.dat file pointer */
1.1 Link the
11
12 if ( ( cfPtr = fopen( "clients.dat", "w" ) ) == NULL )
pointer to a
13
14
printf( "File could not be opened\n" );
else {
file
15 printf( "Enter the account, name, and balance.\n" );
16
17
printf( "Enter EOF to end input.\n" );
printf( "? " );
2. Input data
18 scanf( "%d%s%lf", &account, name, &balance );
19 2.1 Write to
20 while ( !feof( stdin ) ) {
21
22
fprintf( cfPtr, "%d %s %.2f\n",
account, name, balance );
file
23
24
printf( "? " );
scanf( "%d%s%lf", &account, name, &balance );
(fprintf)
25 }
26 3. Close file
27 fclose( cfPtr );
28 }
29
30 return 0;
31 }
Enter the account, name, and balance.
Enter EOF to end input.
? 100 Jones 24.98
? 200 Doe 345.67
? 300
? 400
White 0.00
Stone -42.16 Program
? 500 Rich 224.62
? Output
Reading Data from a Sequential
Access File
• Reading a sequential access file
– Create a FILE pointer, link it to the file to read
myPtr = fopen( "myFile.dat", "r" );
– Use fscanf to read from the file
• Like scanf, except first argument is a FILE pointer
fscanf( myPtr, "%d%s%f", &myInt, &myString,
&myFloat );
– Data read from beginning to end
– File position pointer
• Indicates number of next byte to be read / written
• Not really a pointer, but an integer value (specifies byte
location)
• Also called byte offset
– rewind( myPtr )
• Repositions file position pointer to beginning of file (byte 0)
1 /* Fig. 11.7: fig11_07.c
2 Reading and printing a sequential file */
3 #include <stdio.h>
1. Initialize
4
5 int main() variables
6 {
7 int account;
8 char name[ 30 ];
9 double balance;
10
11
FILE *cfPtr; /* cfPtr = clients.dat file pointer */
1.1 Link
12 if ( ( cfPtr = fopen( "clients.dat", "r" ) ) == NULL )
13
14
printf( "File could not be opened\n" );
else {
pointer to file
15 printf( "%-10s%-13s%s\n", "Account", "Name", "Balance" );
16 fscanf( cfPtr, "%d%s%lf", &account, name, &balance );
17
18 while ( !feof( cfPtr ) ) {
19 printf( "%-10d%-13s%7.2f\n", account, name, balance ); 2. Read data
20 fscanf( cfPtr, "%d%s%lf", &account, name, &balance );
21
22
} (fscanf)
23 fclose( cfPtr );
24
25
} 2.1 Print
26 return 0;
27 }
Account Name Balance
100 Jones 24.98
200
300
Doe
White
345.67
0.00
3. Close file
400 Stone -42.16
500 Rich 224.62
1 /* Fig. 11.8: fig11_08.c
2 Credit inquiry program */
3 #include <stdio.h>
4
5
6
int main()
{
1. Initialize
7
8
int request, account;
double balance;
variables
9 char name[ 30 ];
10 FILE *cfPtr;
11
12
13
if ( ( cfPtr = fopen( "clients.dat", "r" ) ) == NULL )
printf( "File could not be opened\n" );
2. Open file
14 else {
15 printf( "Enter request\n"
16 " 1 - List accounts with zero balances\n"
17 " 2 - List accounts with credit balances\n" 2.1 Input
18 " 3 - List accounts with debit balances\n"
19 " 4 - End of run\n? " ); choice
20 scanf( "%d", &request );
21
22 while ( request != 4 ) {
23 fscanf( cfPtr, "%d%s%lf", &account, name,
24 &balance ); 2.2 Scan files
25
26 switch ( request ) {
27 case 1:
28 printf( "\nAccounts with zero "
29 "balances:\n" );
3. Print
30
31 while ( !feof( cfPtr ) ) {
32
33 if ( balance == 0 )
34 printf( "%-10d%-13s%7.2f\n",
35 account, name, balance );
36
37 fscanf( cfPtr, "%d%s%lf",
38 &account, name, &balance ); 2.2 Scan files
39 }
40
41 break;
42 case 2:
43
44
printf( "\nAccounts with credit "
"balances:\n" );
3. Print
45
46 while ( !feof( cfPtr ) ) {
47
48 if ( balance < 0 )
49 printf( "%-10d%-13s%7.2f\n",
50 account, name, balance );
51
52 fscanf( cfPtr, "%d%s%lf",
53 &account, name, &balance );
54 }
55
56 break;
57 case 3:
58 printf( "\nAccounts with debit "
59 "balances:\n" );
60
61 while ( !feof( cfPtr ) ) {
62
63 if ( balance > 0 )
64 printf( "%-10d%-13s%7.2f\n",
65 account, name, balance );
66
67 fscanf( cfPtr, "%d%s%lf",
68 &account, name, &balance );
69
70
}
3.1 Close file
71 break;
72 }
73
74 rewind( cfPtr );
75 printf( "\n? " );
76 scanf( "%d", &request );
77 }
78
79 printf( "End of run.\n" );
80 fclose( cfPtr );
81 }
82
83 return 0;
84 }
Enter request
1 - List accounts with zero balances
2 - List accounts with credit balances
3 - List accounts with debit balances
4 - End of run
? 1 Program
Accounts with zero balances:
300 White 0.00
Output
? 2

Accounts with credit balances:


400 Stone -42.16

? 3

Accounts with debit balances:


100 Jones 24.98
200 Doe 345.67
500 Rich 224.62
? 4
End of run.
Reading Data from a Sequential Access File
• Sequential access file
– Cannot be modified without the risk of destroying other
data
– Fields can vary in size
• Different representation in files and screen than internal
representation
• 1, 34, -890 are all ints, but have different sizes on disk
300 White 0.00 400 Jones 32.87 (old data in file)
If we want to change White's name to Worthington,

300 Worthington 0.00

300 White 0.00 400 Jones 32.87


Data gets overwritten

300 Worthington 0.00ones 32.87


Random Access Files
• Random access files
– Access individual records without searching through other
records
– Instant access to records in a file
– Data can be inserted without destroying other data
– Data previously stored can be updated or deleted without
overwriting
• Implemented using fixed length records
– Sequential files do not have fixed length records
0 100 200 300 400 500

}byte offsets
}
}
}
}
}

100 100 100 100 100


}100
bytes bytes bytes bytes bytes bytes
Creating a Random Access File
• Data in random access files
– Unformatted (stored as "raw bytes")
• All data of the same type (ints, for example) uses
the same amount of memory
• All records of the same type have a fixed length
• Data not human readable
Creating a Random Access File
• Unformatted I/O functions
– fwrite
• Transfer bytes from a location in memory to a file
– fread
• Transfer bytes from a file to a location in memory
– Example:
fwrite( &number, sizeof( int ), 1, myPtr );
• &number – Location to transfer bytes from
• sizeof( int ) – Number of bytes to transfer
• 1 – For arrays, number of elements to transfer
– In this case, "one element" of an array is being transferred
• myPtr – File to transfer to or from
Creating a Random Access File
• Writing structs
fwrite( &myObject, sizeof (struct
myStruct), 1, myPtr );
– sizeof – returns size in bytes of object in
parentheses
• To write several array elements
– Pointer to array as first argument
– Number of elements to write as third argument
Writing Data Randomly to a Random
Access File
• fseek
– Sets file position pointer to a specific position
– fseek( pointer, offset, symbolic_constant );
• pointer – pointer to file
• offset – file position pointer (0 is first location)
• symbolic_constant – specifies where in file we are
reading from
• SEEK_SET – seek starts at beginning of file
• SEEK_CUR – seek starts at current location in file
• SEEK_END – seek starts at end of file
Reading Data Sequentially from
a Random Access File
• fread
– Reads a specified number of bytes from a file
into memory
fread( &client, sizeof (struct
clientData), 1, myPtr );
– Can read several fixed-size array elements
• Provide pointer to array
• Indicate number of elements to read
– To read multiple elements, specify in third
argument
The ftell() Functions
• You can obtain the value of the current file position
indicator by calling the ftell() function.
• The syntax for the ftell() function is
long ftell(FILE *stream);
Here stream is the file pointer associated with an opened
file. The ftell() function returns the current value of the
file position indicator.
• The value returned by the ftell() function represents the
number of bytes from the beginning of the file to the
current position pointed to by the file position indicator.
• If the ftell() function fails, it returns -1L (that is, a long
value of minus 1).
Example on Random access to a file.
#include <stdio.h>
enum {SUCCESS, FAIL, MAX_LEN = 80};
void PtrSeek(FILE *fptr);
long PtrTell(FILE *fptr);
void DataRead(FILE *fptr);
int ErrorMsg(char *str);
main(void)
{ FILE *fptr;
char filename[]= “test.txt";
int reval = SUCCESS;
if ((fptr = fopen(filename, "r")) == NULL){
reval = ErrorMsg(filename);
} else {
PtrSeek(fptr);
fclose(fptr);
}
return reval;
}
/* function definition */
void PtrSeek(FILE *fptr)
{
long offset1, offset2, offset3;
offset1 = PtrTell(fptr);
DataRead(fptr);
offset2 = PtrTell(fptr);
DataRead(fptr);
offset3 = PtrTell(fptr);
DataRead(fptr);
printf("\nRe-read the test:\n");
/* re-read the third verse of the test */
fseek(fptr, offset3, SEEK_SET);
DataRead(fptr);
/* re-read the second verse of the test */
fseek(fptr, offset2, SEEK_SET);
DataRead(fptr);
/* re-read the first verse of the test */
fseek(fptr, offset1, SEEK_SET);
DataRead(fptr);
}
/* function definition */
long PtrTell(FILE *fptr)
{
long reval;
reval = ftell(fptr);
printf("The fptr is at %ld\n", reval);
return reval;
}
/* function definition */
void DataRead(FILE *fptr)
{ char buff[MAX_LEN];
fgets(buff, MAX_LEN, fptr);
printf("---%s", buff);
}
/* function definition */
int ErrorMsg(char *str)
{
printf("Cannot open %s.\n", str);
return FAIL;
}
OUTPUT

The fptr is at 0
---Leading me along
The fptr is at 18
---my shadow goes back home
The fptr is at 44
---from looking at the moon.
Re-read the test:
---from looking at the moon.
---my shadow goes back home
---Leading me along
The rewind() Function
• Sometimes you might want to reset the file
position indicator and put it at the beginning
of a file. There is a handy C function, called
rewind(), that can be used to rewind the file
position indicator.
• The syntax for the rewind() function is
void rewind(FILE *stream);
• rewind(fptr); is equivalent to this:
(void)fseek(fptr, 0L, SEEK_SET);
More Examples of Disk File I/O
#include <stdio.h>
enum {SUCCESS, FAIL, MAX_NUM = 3};

void DataWrite(FILE *fout);


void DataRead(FILE *fin);
int ErrorMsg(char *str);
main(void)
{
FILE *fptr;
char filename[]= "double.bin";
int reval = SUCCESS;
if ((fptr = fopen(filename, "wb+")) == NULL){
reval = ErrorMsg(filename);
} else {
DataWrite(fptr);
rewind(fptr); /* reset fptr */
DataRead(fptr);
fclose(fptr);
return reval;
}
}
/* function definition */
void DataWrite(FILE *fout)
{
int i;
double buff[MAX_NUM] = {
123.45,
567.89,
100.11};

printf("The size of buff: %d-byte\n", sizeof(buff));


for (i=0; i<MAX_NUM; i++){
printf("%5.2f\n", buff[i]);
fwrite(&buff[i], sizeof(double), 1, fout);
}
}
/* function definition */
void DataRead(FILE *fin)
{
int i;
double x;

printf("\nRead back from the binary file:\n");


for (i=0; i<MAX_NUM; i++){
fread(&x, sizeof(double), 1, fin);
printf("%5.2f\n", x);
}
}
/* function definition */
int ErrorMsg(char *str)
{
printf("Cannot open %s.\n", str);
return FAIL;
}
OUTPUT

The size of buff: 24-byte


123.45
567.89
100.11

Read back from the binary file:


123.45
567.89
100.11

You might also like