Вы находитесь на странице: 1из 49

FILE INPUT/OUTPUT IN C

M.Noorazlan Shah, Norhidayah, Lizawati


Concept of File
File an external collection of related data treated as a unit.
The contents of primary memory are lost when the computer is
shut down, need files to store data in more permanent form.
Two broad classes of files:
Text files store data as graphic characters represent numeric data Text files store data as graphic characters represent numeric data
and each line of data ends with a newline character.
Binary files store data in internal computer formats, such integer
and floating point numbers.
Files stored in secondary storage devices.
Buffer temporary storage area that holds data while they
are being transferred to or from memory.
Buffers
A buffer is a special work area that holds data as the
computer transfers them to/from memory.
Buffers help to synchronize data the physical devices with the
program.
The physical requirements of the devices can deliver more
data for input than a program can use at any one time. The data for input than a program can use at any one time. The
buffer handles the overflow data until a program can use it.
Moreover, the buffer also holds data until it is efficient to write
that data to the storage device for output.
Streams
All input and output is performed with streams.
A "stream" is a sequence of characters organized into lines.
Each line consists of zero or more characters and ends with the Each line consists of zero or more characters and ends with the
"newline" character.
ANSI C standards specify that the system must support lines
that are at least 254 characters in length (including the
newline character).
Streams
In C, we input/output data using streams. We can associate a
stream with a device (i.e. the terminal) or with a file.
C supports two types of files
Text Stream Files
Binary Stream Files
Text Streams and Binary Streams
Text streams consist of sequential characters divided into lines.
Each line terminates with the newline character (\n).
Binary streams consist of data values such as integers, floats or
complex data types, using their memory representation. complex data types, using their memory representation.
Files and Streams
In C, each file is simply a sequential stream of bytes. C
imposes no structure on a file.
A file must first be opened properly before it can be accessed
for reading or writing. When a file is opened, a stream is
associated with the file. associated with the file.
Successfully opening a file returns a pointer to (i.e., the address
of) a file structure, which contains a file descriptor and a file
control block.
Types of Streams
Three standard file streams called standard input, standard
output and standard error.
File streams defined in standard input/output header file
(<stdio.h>) and referred to as stdin, stdout and stderr.
Standard input stream is called "stdin" and is normally connected to Standard input stream is called "stdin" and is normally connected to
the keyboard
Standard output stream is called "stdout" and is normally connected
to the display screen.
Standard error stream is called "stderr" and is also normally
connected to the screen.
Steps in Processing Files
1. Create the stream via a pointer variable using the FILE
structure (file declaration).
2. Open the file, associating the stream name with the file name.
3. Read or write the data.
4. Close the file. 4. Close the file.
File Declaration
Data type FILE is used to define a file pointer for
use in file operations.
FILE is defined in the header file stdio.h
Example: FILE *f_in;
declares that f_in is a pointer variable of type
FILE. They will be assigned the address of a file
descriptor, that is, an area of memory that will be
associated with an input or output stream.
FILE *filePointerName;
Opening Files
Before reading or writing to a file, the declared file must first
open the file and assign the address of its file descriptor (or
structure) to the file pointer variable.
Function that prepares a file for processing is fopen().
To open file, need to specify the filename and its mode. To open file, need to specify the filename and its mode.
Filename a string that supplies the name of the file as it is
known to the external world.
File mode a string that tells C how you intend to use the file.
fopen (fileName, mode);
Opening Files (cont..)
File mode:
Mode Meaning
r Open file for reading
-If file exists, the marker is positioned at beginning. -If file exists, the marker is positioned at beginning.
-If file doesnt exists, error returned.
w Open text file for writing
-If file exists, it is emptied.
-If file doesnt exists, it is created.
a Open text file for append
-If file exists, the marker is positioned at end.
-If file doesnt exists, it is created.
The statement:
would open the file mydata.dat for input (reading).
Opening Files (cont..)
f_in = fopen(mydata.dat, r);
would open the file mydata.dat for input (reading).
The statement:
would open the file results.txt for output (writing).
Once the files are open, they stay open until you close them or
end the program (which will close all files.)
f_out = fopen(results.txt, w);
More on File Open
The file mode tells C how the program will use the file.
The filename indicates the system name and location for the
file.
We assign the return value of fopen to our pointer variable:
spData = fopen(MYFILE.DAT, w); spData = fopen(MYFILE.DAT, w);
spData = fopen(A:\\MYFILE.DAT, w);
More on File Open Modes
Closing Files
Function fclose() is used to close the files.
Closing files are optional since it does not effect to the
execution.
fclose(filePointerName);
The statements:
will close the files and release the file descriptor space and
I/O buffer memory.
fclose(filePointerName);
fclose(f_in);
fclose(f_out);
Open and Close Errors
Errors occurs when the external filename in the open function
call does not match a name on the disk.
Make sure the file stream has successfully opened. If fail, file
variable contains NULL, which is a C-defined constant for no
address.
The fclose function return an integer that is zero if the close
succeeds and EOF if there is an error.
EOF is defined in the standard input/output header file by the
system programmer.
Function as an expression in an if statement is used to ensure
that the file opened and closed successfully.
Testing for Successful Open
If the file was not able to be opened, then the value returned
by the fopen routine is NULL.
For example, let's assume that the file mydata.dat does not
exist. Then:
FILE *fptr1 ;
fptr1 = fopen ( "mydata.dat", "r") ;
if (fptr1 == NULL)
{
printf ("File 'mydata' does not exist.\n");
exit(-1);
}
FILE *fpTemps;
if ((fpTemps = fopen (TEMPS.DAT, r)) == NULL)
{
printf(\aERROR opening TEMPS.DAT\n);
Testing for Successful Open & Close
printf(\aERROR opening TEMPS.DAT\n);
exit(-1);
}
if (fclose(fpTemps) == EOF)
{
printf(\aERROR closing TEMPS.DAT\n);
exit(-1);
}
Writing to Files
To write to a file, the file must be opened in a w mode
Functions writing to files:
fprintf() write various data type at one time
fputc(), fputch(), fputchar() write a
character at one time (char data type) character at one time (char data type)
fputs() write a line of string at one time (string data
type)
Example 1: Writing to Files
Writing name and age to biodata.text by using
fprintf():
#include <stdio.h>
main()
{
FILE *fp;
Enter your name > Daniel
Enter your age > 21 FILE *fp;
fp = fopen("biodata.txt", "w");
char name[20];
int age;
printf("Enter your name > ");
scanf ("%s", name);
printf("Enter your age > ");
scanf("%d", &age);
fprintf(fp, "%s\t%d\n", name, age);
fclose(fp);
return 0;
}
Enter your age > 21
output
Daniel 21
biodata.txt
Example 2: Writing to Files
Writing students name, age and id to student.dat
by using fputs() and fprintf():
#include <stdio.h>
main()
{
Siti Aishah
24 1001
int age = 20, id = 1002;
FILE *fp;
fp = fopen("student.dat", "w");
fputs("Siti Aishah", fp);
fprintf(fp, "\n%d\t%d\n", 24, 1001);
fputs("Nazren Hanif", fp);
fprintf(fp, "\n%d\t%d\n", age, id);
fclose(fp);
return 0;
}
24 1001
Nazren Hanif
20 1002
student.dat
Example 3: Writing to Files
Writing name and age to name.text by using
fputc():
#include <stdio.h>
main()
{
Enter your name (keyin . to stop) >
Siti Munirah.
{
FILE *fp;
fp = fopen("name.txt", "w");
int name;
printf("Enter your name (keyin '.' to stop)> ");
do
{
name = getc(stdin);
fputc(name, fp);
} while(name != '.');
fclose(fp);
return 0;
}
Siti Munirah.
output
Siti Munirah.
name.txt
Example 4: Append to Files
Append to the existing file in the a mode
#include <stdio.h>
main()
{
int age = 20, id = 1002;
Siti Aishah
24 1001
Nazren Hanif
20 1002
int age = 20, id = 1002;
FILE *fp;
fp = fopen("student.dat", a");
fputs(Hakim Danish", fp);
fprintf(fp, "\n%d\t%d\n", 20, 1003);
fputs(Liana Ahmad", fp);
fprintf(fp, "\n%d\t%d\n", 21, 1004);
fclose(fp);
return 0;
}
20 1002
Hakim Danish
20 1003
Liana Ahmad
21 1004
student.dat
Reading from Files
To read from a file, the file must be opened in a r mode.
Functions to read from files:
fscanf() read various data type at one time
fgetc(), fgetch(), fgetchar() read a
character at one time (char data type) character at one time (char data type)
fgets() read a line at one time (string data type)
File written using fprintf() function is recommended to
read by using fscanf() function.
End of Files
The end-of-file indicator informs the program when there are
no more data (no more bytes) to be processed.
There are a number of ways to test for the end-of-file
condition. One is to use the feof() function which returns a
true or false condition. true or false condition.
Example:
feof (filePointerName)
fscanf (f_in, "%d", &var) ;
if (feof(f_in))
{
printf ("End-of-file encountered.\n);
}
Another way is to use the value returned by the reading file
functions (fcanf(), fgetc(), etc):
int istatus ;
istatus = fscanf(f_in, "%d", &var) ;
End of Files (cont..)
istatus = fscanf(f_in, "%d", &var) ;
if (istatus == EOF)
{
printf ("End-of-file encountered.\n) ;
}
Example 1: Reading from Files
Reading file student.dat using fgets() and fscanf()
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("student.dat", "r");
if (fp==NULL)
{
printf("Error: Cannot open file");
exit(-1);
}
char name[30];
int age, i=0;
int id;
Example 1: Reading from Files
(cont..)
while(!feof(fp))
{
fgets(name, 30,fp);
fscanf(fp,"%d\t",&age);
fscanf(fp,"%d\n",&id);
Student 1: Siti Aishah
age: 24 id: 1001
Student 2: Nazren Hanif
age: 20 id: 1002
printf("\n\nStudent %d: ",i+1);
printf("%s", name);
printf("\t age: %d",age);
printf("\t id: %d",id);
i++;
}
fclose(fp);
return 0;
}
age: 20 id: 1002
Student 3: Hakim Danish
age: 20 id: 1003
Student 4: Liana Ahmad
age: 21 id: 1004
output
Example 2: Reading from Files
Reading file biodata.txt using fgetc()
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("biodata.txt", "r");
if (fp==NULL)
{
printf("Error: Cannot open file");
exit(-1);
}
char data;
char text[20];
int i=0;
Example 2: Reading from Files
(cont..)
while((data=fgetc(fp))!= EOF)
{
putchar(data);
}
Daniel 21
}
fclose(fp);
return 0;
}
output
Example 3: Content of file
Example 3: Read data from file
#include<stdio.h>
int main()
{
char matric[12];
char name[30];
float pointer; float pointer;
FILE *cfPtr;
if((cfPtr=fopen(student.dat","r"))==NULL)
{
printf("File could not be opened");
}
Example 3: Read data from file
(cont..)
else
{
printf("%s\t\t%s\t%s\n","NAME",MATRIC NO",POINTER));
fscanf(cfPtr,"%s%s%f",name,matric,&pointer);
while(!feof(cfPtr))
{{
fscanf(cfPtr,"%s%s%f",name,matric,&pointer);
printf("%s\t\t%s\t%.2f\n",name,matric,pointer);
}
fclose(cfPtr);
}
return 0;
}
Example 3: Output of the program
Example 4a: Reading data from
file
#include<stdio.h>
int main()
{
int acc;
char name[30];
float balance;
FILE *cfPtr;
if((cfPtr=fopen("client.dat", "r"))==NULL)
{
printf("File could not be opened\n\n");
}
else
{
fscanf(cfPtr,"%d %s %f", &acc, name, &balance);
printf("%d %s %f\n", acc, name, balance);
fclose(cfPtr);
}
fclose(cfPtr);
return 0;
}
Example 4a: Output if the file does
not exist
Example 4b: Writing data into file
#include<stdio.h>
int main()
{
int acc;
char name[30];
float balance;
FILE *cfPtr;
if((cfPtr=fopen("client.dat", "w"))==NULL)
printf("File could not be opened"); printf("File could not be opened");
else
{
printf("Enter details: \n");
scanf("%d", &acc);
scanf("%s", name);
scanf("%f", &balance);
fprintf(cfPtr,"%d %s %f", acc, name, balance);
printf(%d\t%s\t%.2f,acc,name,balance);
}
fclose(cfPtr);
return 0;
}
Example 4b: Output of the
program
Example 5: Reading & Writing Files
#include <stdio.h>
int main ( )
{
FILE *outfile, *infile ;
int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata.txt", "w") ; outfile = fopen ("testdata.txt", "w") ;
fprintf (outfile, "%6.2f%2d%5.2f", a, b, c) ;
fclose (outfile) ;
infile = fopen ("testdata.txt", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf ("%6.2f%2d%5.2f\n", a, b, c) ;
printf ("%6.2f,%2d,%5.2f\n", e, f, g) ;
}
Output:
13.72 5 6.68
13.72, 5, 6.68
Example 6: Copying file from
another file
#include <stdio.h>
main()
{
FILE *f_in, *f_out;
char fOri_name[30];
char fNew_name[30];
int data;
printf("Enter file name to copy from: ");
gets(fOri_name);
printf("Enter file name to copy to: ");
gets(fNew_name);
Example 6: Copying file from
another file (cont..)
if((f_in=fopen(fOri_name,"r"))==NULL)
{
printf("\n\n*** %s is not exist ***\n", fOri_name);
exit(-1);
}
if((f_out=fopen(fNew_name,"w"))==NULL)
{
printf("\n\n*** Error to open %s ***\n", fNew_name); printf("\n\n*** Error to open %s ***\n", fNew_name);
exit(-1);
}
printf("\nCopying file...\n");
while((data=fgetc(f_in)) != EOF)
{
fputc(data, f_out);
}
printf("\nFinish copying file.\n");
fclose(f_in);
fclose(f_out);
return 0;
}
Example 7: Convert a text file to all
UPPERCASE
#include <stdio.h>
#include<ctype.h>
main()
{
FILE *in, *out ;
char c ; char c ;
in = fopen ("infile.txt", "r") ;
out = fopen ("outfile.txt", "w") ;
while ((c = getc (in)) != EOF)
putc (toupper (c), out);
fclose (in) ;
fclose (out) ;
}
Some Points
How to check EOF condition when using fscanf?
Use the function feof
if (feof (fp))
printf (\n Reached end of file) ;
How to check successful open? How to check successful open?
For opening in r mode, the file must exist.
if (fp == NULL)
printf (\n Unable to open file) ;
Input Redirection
So far we have seen that when we need to read data
from the keyboard we use scanf and when we need to
read from a file we use fscanf.
In reality, scanf means reading from standard input,
and that usually means the keyboard. and that usually means the keyboard.
Output Redirection
We can do redirection also for the output.
So far we have seen that when we need to write
data to the screen we use printf and when we
need to write to a file we use fprintf.
printf really means writing to standard output,
and that usually means the screen.
Redirection vs File I/O
Advantages:
No need to modify program when file name changes.
No need to open/close files in the program.
Drawbacks:
The keyboard and/or screen are rendered useless.
You are limited to one input file and one output file.
You cannot use file and keyboard (or monitor) in the same
program.
Conclusion:
Unless you need more than one file or need access to keyboard
and/or monitor in your program, novice programmers are
encouraged to use redirection.
Summary (Reading from Files)
To do that you need first to declare the file
FILE *in;
/* notice that FILE is all upper case and the * before the name of the
file variable. */
Then the file must be opened
in = fopen ("mydata.txt", "r"); in = fopen ("mydata.txt", "r");
/* must exist on your disk! */
To read from the file, we use fscanf() etc
fscanf (in, "%d", &temp);
The file must be closed when not longer needed
fclose (in);
Summary (Writing to Files)
To do that you need first to declare the file
FILE *out;
Then the file must be opened
out = fopen ("result.txt", "w");
/* w is for write it will create a new file on your disk */ /* w is for write it will create a new file on your disk */
To write to the file, we use fprintf() etc.
fprintf (out, "%d", temp);
The file must be closed when not longer needed
fclose (out);

Вам также может понравиться