Lecture13 Data Files
Lecture13 Data Files
PROGRAMMING
Bhaskar Shrestha
National College of Computer Studies
Tribhuvan University
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
Information stored in a data file can be accessed and altered
whenever necessary
Bhaskar Shrestha
Program Input/Output
A C program keeps data in RAM in the form of variables
Data can come from some location external to the
program
Data moved from an external location into RAM, where the
program can access it, is called input
Keyboard and disk files are the most common sources of
program input
I/O Devices
Input sources and output destinations are collectively referred to
as devices
The keyboard is a device, the screen is a device, and so on
Some devices (the keyboard) are for input only, others (the
screen) are for output only, and still others (disk files) are for both
input and output
Input sources and output destinations are collectively referred to
as devices
The keyboard is a device, the screen is a device, and so on
Some devices (the keyboard) are for input only, others (the
screen) are for output only, and still others (disk files) are for both
input and output
Bhaskar Shrestha
Streams (1/2)
Whatever the device, and whether its performing input
or output, C carries out all input and output operations
by means of streams
A stream is a sequence of bytes of data
A sequence of bytes flowing into a program is an input stream
A sequence of bytes flowing out of a program is an output
stream
Advantages of Streams
By focusing on streams, you dont have to worry as much
about where theyre going or where they originated
With streams, input/output programming is device independent
Bhaskar Shrestha
Streams (2/2)
Programmers dont need to write special input/output functions
for each device (keyboard, disk, and so on)
Text Streams
A text stream consists of sequence of characters, such as text
data being sent to the screen
Text streams are organized into lines, which can be up to 255
characters long and are terminated by an end-of-line, or newline,
character
Certain characters in a text stream are recognized as having
special meaning, such as the newline character
In a text stream, certain character translations may occur as
required by the host environment
For example, a newline may be converted to a carriage return/linefeed pair
Bhaskar Shrestha
Binary Streams
A binary stream is a sequence of bytes
A binary stream can handle any sort of data, including,
but not limited to, text data
Bytes of data in a binary stream arent translated or
interpreted in any special way; they are read and written
exactly as-is
In text stream, end of file is determined by a special
character having ASCII value 26, but in binary stream
end of file is determined by the directory listing of host
environment
Bhaskar Shrestha
Predefined Streams
ANSI C has three predefined streams
These streams are automatically opened when a C program starts
executing and are closed when the program terminates
All standard streams are text streams
Whenever you have used the printf or puts functions to display
text on-screen, you have used the stdout stream
Likewise, when you use gets
or scanf to read keyboard input,
you use the stdin stream
Name Stream
Device
stdin
Keyboard
Standard input
Screen
stderr
Screen
Bhaskar Shrestha
Standard error
10
Bhaskar Shrestha
11
Function
fopen
Opens a file
fclose
Closes a file
putc, fputc
getc, fgetc
fgets
fputs
fprintf
fscanf
feof
ferror
fflush
Flushes a file
Bhaskar Shrestha
12
Files
In C, a file may be from a disk file to a terminal or printer
You associate a stream with a specific file by performing an open
operation
Once a file is open, information can be exchanged between it and
your program
You can read from or write to the file
Bhaskar Shrestha
13
Opening a File
The process of creating a stream linked to a disk file is called
opening the file
When you open a file, it becomes available for reading, writing, or
both
The fopen function opens a stream for use and links a file with
that stream
FILE* fopen(const char *filename,const char *mode);
14
15
Meaning
Open a new file for writing only. If a file with the specified name exists,
it will be destroyed and a new file is created
Opens an existing file for appending. A new file will be created if the
specified file doesnt exists. New data is appended to the end of the file.
r+
w+
Open a new file for both reading and writing. If a file with specified
name exists, it will be destroyed and a new file will be created
a+
Open an existing file for both reading and appending. A new file will be
created if the file with the specified name does not exist.
Bhaskar Shrestha
16
fopen Examples
FILE *fp;
fp = fopen("c:\\test.txt", "w");
if (fp == NULL) {
printf("Cannot open file\n");
exit(1);
}
FILE *fp;
fp = fopen("c:\\test.txt", "r+");
if (fp == NULL) {
printf("Cannot open file\n");
exit(1);
}
Bhaskar Shrestha
17
Closing a File
When youre done using the file, you must close it
The fclose function closes a stream that was opened by a call to
fopen
int fclose(FILE *fp);
where fp is the file pointer returned by the call to fopen
Returns 0 if file is successfully closed
Returns EOF is an error occurs
18
FILE *fp;
char filename[80];
char mode[4];
char response;
do
{
/* input filename and mode */
printf("Enter filename: ");
scanf(" %[^\n]", filename);
printf("Enter mode to open: ");
scanf("%s", mode);
/* try to open the file */
fp = fopen(filename, mode);
if (fp != NULL) /* success? */
{
printf("Successfully opened %s in %s mode\n", filename, mode);
fclose(fp); /* we don't do anything to the file, so close it */
}
else
printf("Failed to open %s in %s mode\n", filename, mode);
printf("Another (Y/N): ");
scanf(" %c", &response); Bhaskar Shrestha
} while (response == 'Y' || response == 'y');
19
Formatted output
to save formatted data to a file
Bhaskar Shrestha
20
Direct/Unformatted output
to save the contents of a section of memory directly to a disk
file
Use for binary streams only
direct output is the best way to save data for later use by a C
program
Bhaskar Shrestha
21
22
}
Bhaskar Shrestha
23
ch = getc(fp);
while (ch != EOF) {
putchar(ch);
ch = getc(fp);
}
Bhaskar Shrestha
24
25
26
fprintf works just like printf, except that it sends its output
to the stream fp specified in the argument list
fprintf returns the number of characters actually printed. If an
error occurs, a negative number is returned
Bhaskar Shrestha
27
FILE *fp;
float array[5] = {10.2, 5.0, 5.55, 6.005, 135};
int i;
fp = fopen("test.txt", "w");
if (fp == NULL) {
printf("Unable to open output file test.txt\n");
exit(1);
}
fprintf(fp, "Here are the %d values of the array:\n", 5);
for (i = 0; i < 5; i++)
fprintf(fp, "array[%d] = %f\n", i, array[i]);
fclose(fp);
28
The function fscanf works exactly the same as scanf, except that
characters are taken from the specified stream rather than from
keyboard
fscanf returns the number of arguments that were actually
assigned values. A return value of EOF means that a failure
occurred before the first assignment was made
Bhaskar Shrestha
29
FILE *fp;
This program reads a string and an
integer from the keyboard and writes
char s[80];
them to a disk file called test.txt. The
int t;
program then reads the file and
displays the information on the
fp = fopen("test.txt", "w");
screen. After running the program,
if (fp == NULL) {
examine the test.txt file. As you will
printf("Cannot open file\n"); see, it contains human-readable text.
exit(1);
}
printf("Enter a string and number: ");
scanf("%s%d", s, &t);
fprintf(fp, "%s %d", s, t); /* write to file */
fclose(fp);
fp = fopen("test.txt", "r");
if (fp == NULL) {
printf("Cannot open file\n");
exit(1);
}
fscanf(fp, "%s%d", s, &t); /* read from file */
30
printf("%s %d", s, t); Bhaskar Shrestha
31
32
fwrite examples
double x = 12e-6;
/* write a double value x */
fwrite(&x, sizeof(double), 1, fp);
int arr[10];
...
/* write an array arr*/
fwrite(arr, sizeof(int), 10, fp);
struct address addr[50], myaddr;
...
/* write a structure variable myaddr*/
fwrite(&myaddr, sizeof(struct address), 1, fp);
/* write the entire structure array addr */
fwrite(addr, sizeof(struct address), 50, fp);
Bhaskar Shrestha
33
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
Bhaskar Shrestha
34
fread examples
double x;
/* read a double value x */
fread(&x, sizeof(double), 1, fp);
int arr[10];
...
/* read an array arr*/
fread(arr, sizeof(int), 10, fp);
struct address addr[50], myaddr;
...
/* read a structure variable myaddr*/
fread(&myaddr, sizeof(struct address), 1, fp);
/* read entire structure array addr */
fread(addr, sizeof(struct address), 50, fp);
Bhaskar Shrestha
35
File Buffer
When a stream linked to a disk file is created, a buffer is
automatically created and associated with the stream
A buffer is a block of memory used for temporary
storage of data being written to and read from the file
Buffers are needed because disk drives are blockoriented devices, which means that they operate most
efficiently when data is read and written in blocks of a
certain size
The size of the ideal block differs, depending on the
specific hardware in use
Bhaskar Shrestha
36
Use of Buffer
Buffer serves as an interface between the stream and the disk
hardware
As a program writes data to the stream, the data is saved in the
buffer until the buffer is full, and then the entire contents of the
buffer are written, as a block, to the disk
An analogous process occurs when reading data from a disk file
During program execution, data that a program wrote to the disk
might still be in the buffer, not on the disk
If your program hangs up, if there's a power failure, or if some other
problem occurs, the data that's still in the buffer might be lost, and you
won't know what's contained in the disk file
Bhaskar Shrestha
37
38
Bhaskar Shrestha
39
40
Bhaskar Shrestha
41
42
Origin
Macro Name
SEEK_CUR
End of file
SEEK_END
Bhaskar Shrestha
43
44
Function
clearerr
fgetpos
freopen
fsetpos
remove
Deletes a file
rename
rewind
setbuf
tmpfile
tmpnam
ungetc