What is a file?
• A named collection of data, stored in secondary storage (typically).• Typical operations on files:
– Open
– Read
– Write
– Close
• How is a file stored?
– Stored as sequence of bytes, logically contiguous (may not be physically contiguous on disk).
– The last byte of a file contains the end-of-file character (EOF), with ASCII code 1A (hex).
– While reading a text file, the EOF character can be checked to know the end.
• Two kinds of files:
– Text :: contains ASCII codes only
– Binary :: can contain non-ASCII characters
• Image, audio, video, executable, etc.
• To check the end of file here, the file size value (also stored on disk) needs to be checked.
File handling in C
• In C we use FILE * to represent a pointer to a file.• fopen is used to open a file. It returns the special value NULL to indicate that it is unable to open the file.
FILE *fptr;
char filename[]= "file2.dat";
fptr = fopen (filename,"w");
if (fptr == NULL) {
printf (“ERROR IN FILE CREATION”);
/* DO SOMETHING */
}
Modes for opening files
• The second argument of fopen is the mode in which we open the file. There are three modes."r" opens a file for reading.
"w" creates a file for writing, and writes over all previous contents (deletes the file so be careful!).
"a" opens a file for appending – writing on the end of the file.
• We can add a “b” character to indicate that the file is a binary file.
– “rb”, “wb” or “ab”
fptr = fopen (“xyz.jpg”, “rb”);
The exit() function
• Sometimes error checking means we want an "emergency exit" from a program.• In main() we can use return to stop.
• In functions we can use exit() to do this.
• Exit is part of the stdlib.h library.
exit(-1);
in a function is exactly the same as
return -1;
in the main routine
FILE *fptr;char filename[]= "file2.dat";fptr = fopen (filename,"w");if (fptr == NULL) {printf (“ERROR IN FILE CREATION”);/* Do something */exit(-1);}
Writing to a file using fprintf( )
• fprintf() works just like printf() and sprintf() except that its first argument is a file pointer.FILE *fptr;Fptr = fopen ("file.dat","w");/* Check it's open */fprintf (fptr, "Hello World!\n");fprintf (fptr, “%d %d”, a, b);
Reading Data Using fscanf( )
FILE *fptr;
Fptr = fopen (“input.dat”, “r”);
/* Check it's open */
if (fptr == NULL)
{
printf(“Error in opening file \n”);
}
fscanf (fptr, “%d %d”,&x, &y);
Reading lines from a file using fgets( )
We can read a string using fgets().FILE *fptr;char line [1000];/* Open file and check it is open */while (fgets(line,1000,fptr) != NULL){printf ("Read line %s\n",line);}fgets() takes 3 arguments – a string, maximum number of characters to read, and a file pointer. It returns NULL if there is an error (such as EOF).
Closing a file
• We can close a file simply using fclose() and the file pointer.FILE *fptr;char filename[]= "myfile.dat";fptr = fopen (filename,"w");if (fptr == NULL) {printf ("Cannot open file to write!\n");exit(-1);}fprintf (fptr,"Hello World of filing!\n");fclose (fptr);
Three special streams
• Three special file streams are defined in the <stdio.h> header– stdin reads input from the keyboard
– stdout send output to the screen
– stderr prints errors to an error device (usually also the screen)
• What might this do?
fprintf (stdout,"Hello World!\n");
An example program
#include <stdio.h>main()
{
int i;
fprintf(stdout,"Give value of i \n");
fscanf(stdin,"%d",&i);
fprintf(stdout,"Value of i=%d \n",i);
fprintf(stderr,"No error: But an example to show error message.\n");
}
Output of program:
Give value of i
15
Value of i=15
No error: But an example to show error message.
Input File & Output File redirection
• One may redirect the standard input and standard output to other files (other than stdin and stdout).
• Usage: Suppose the executable file is a.out:
$ ./a.out <in.dat >out.dat
scanf() will read data inputs from the file “in.dat”, and printf() will output results on the file “out.dat”.
A Variation
$ ./a.out <in.dat >>out.dat
scanf() will read data inputs from the file “in.dat”, and printf() will append results at the end of the file “out.dat”.
Reading and Writing a character
• A character reading/writing is equivalent to reading/writing a byte.
• Example:
char c;
c = getchar();
putchar(c);
Example: use of getchar() & putchar()
#include <stdio.h>
main()
{
int c;
printf("Type text and press return to
see it again \n");
printf("For exiting press <CTRL D> \n");
while((c = getchar()) != EOF)
putchar(c);
}
No comments:
Post a Comment