eastern mediterranean university school of computing and ... · in this program, we open the file...
TRANSCRIPT
1 | P a g e
Eastern Mediterranean University
School of Computing and Technology
Information Technology
Lecture7 – Text Files
Why files are needed?
When the program is terminated, the entire data is lost in C programming. If you
want to keep large volume of data, it is time consuming to enter the entire data.
A file represents a sequence of byte on the disk where a group of related data is stored. File is
created for permanent storage of data. It is a ready-made structure. In C, we use a structure pointer
of file type to declare a file. C provides a number of functions that help to perform basic file
operations. They are,
o fopen – opens a text file. o fclose – closes a text file. o feof – detects end-of-file marker in a file. o fscanf – reads formatted input from a file. o fprintf – prints formatted output to a file. o fgets – reads a string from a file. o fputs – prints a string to a file. o fgetc – reads a character from a file. o fputc – prints a character to a file.
In order to use files we have to learn about File I/O i.e. how to write information to a file and how
to read information from a file.
As you know, you can have many files on your disk. If you wish to use a file in your programs, then
you must specify which file or files you wish to use.
Specifying the file you wish to use is referred to as opening the file.
When you open a file you must also specify what you wish to do with it i.e. Read from the file,
Write to the file, or both. Because you may use a number of different files in your program, you
must specify when reading or writing which file you wishes to use. This is accomplished by using a
variable called a file pointer.
Every file you open has its own file pointer variable. When you wish to write to a file you specify the
file by using its file pointer variable.
You declare these file pointer variables as follows:
FILE *fp1, *fp2, *fp3;
2 | P a g e
The variables fp1, fp2, fp3 are file pointers. You may use any name you wish.
You should note that a file pointer is simply a variable like an integer or character.
It does not point to a file or the data in a file. It is simply used to indicate which file your I/O
operation refers to.
filename is string literal, which you will use to name your file and access mode can have one of the following values:
Mode Description
r Opens an existing text file for reading purpose.
w Opens a text file for writing, if it does not exist then a new file is created. Here your program will start writing content from the beginning of the file.
a Opens a text file for writing in appending mode, if it does not exist then a new file is created. Here your program will start appending content in the existing file content.
r+ Opens a text file for reading and writing both.
w+ Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist.
a+ Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
The function fopen is one of the Standard Library functions and returns a file pointer which you
use to refer to the file you have opened e.g.
fp = fopen( “prog.txt”, “r”); (old version)
fopen_s(&fp, “prog.txt”, “r”); (new version)
The above statement opens a file called prog.txt for reading and associates the file pointer
fp with the file.
File I/O
The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.
3 | P a g e
The routine getc(fp) is similar to getchar()
and putc(c,fp) is similar to putchar(c).
Thus the statement
c = getc(fp); or c=fgetc(fp);
reads the next character from the file referenced by fp and the statement
putc(c,fp); or fputc(c,fp);
writes the character c into file referenced by fp.
Reading from files
#include "stdafx.h" #include "stdlib.h" int main() { FILE *fp; char b[50],ch; fopen_s(&fp,"test.txt", "r"); if (!fp) { printf("File opening failed"); return EXIT_FAILURE; } fgets(b, sizeof b, fp); //puts(b); printf("%s", b); fclose(fp); return 0; } OR #include "stdafx.h" int main() { FILE *fp; char b[50],ch; fopen_s(&fp,"test.txt", "r"); ch = fgetc(fp); while (ch!=EOF)//OR (!feof(fp)) { printf("%c",ch); ch = fgetc(fp); } //printf("Read Buffer: %s\n", b); fclose(fp); return 0; }
4 | P a g e
In this program, we open the file test.txt for reading. This file must exist for this program to
work.
If the file is empty, we are at the end, so getc/fgetc returns EOF a special value to indicate that
the end of file has been reached. (Normally -1 is used for EOF)
The while loop simply keeps reading characters from the file and displaying them, until the end of
the file is reached.
The function fclose is used to close the file i.e. indicate that we are finished processing this file.
We could reuse the file pointer fp by opening another file.
If you attempt to read from a non-existent file, your program will crash!!
The fopen function was designed to cope with this eventuality. It checks if the file can be opened
appropriately. If the file cannot be opened, it returns a NULL pointer. Thus by checking the file
pointer returned by fopen, you can determine if the file was opened correctly and take
appropriate action e.g.
if ( fp == NULL)
{
printf(“Cannot open for reading \n”, );
exit(1) ; /*Terminate program*/
}
NEW
#include "stdafx.h"
#include "stdlib.h"
int main()
{
FILE *fp;
char b[50],ch;
fopen_s(&fp,"test.txt", "r");
if (!fp) {
perror("File opening failed"); or printf(…);
return EXIT_FAILURE; //OR return 1;
}
ch = fgetc(fp);
5 | P a g e
while (ch != EOF)//OR (!feof(fp))
{
printf("%c", ch);
ch = fgetc(fp);
}
fclose(fp);
return 0;
}
The above code fragment show how a program might check if a file could be opened appropriately.
The function exit() is a special function which terminates your program immediately.
Example 1: Write a program to count the number of lines and characters in a file.
Note: Each line of input from a file or keyboard will be terminated by the newline character
‘\n’. Thus by counting newlines we know how many lines there are in our input.
Count characters in a file #include "stdafx.h" #include "stdlib.h" int main() { FILE *fp; char b[50], ch; int nlines=0, nc = 0; fopen_s(&fp, "test.txt", "r"); if (!fp) { printf("File opening failed"); return EXIT_FAILURE; } ch = fgetc(fp); while (!feof(fp)) { if (ch == '\n') nlines++; nc++; ch = fgetc(fp); } printf("There are %d characters\n", nc); printf("There are %d lines \n", nlines-1); fclose(fp); return 0;
6 | P a g e
}
Writing to files
To write to a file, the file must be opened for writing e.g.
fp = fopen( fname, “w” );
If the file does not exist, it will be created. If the file exists, it will be overwritten! So, be careful
when opening files for writing.
Character Output to Files
The function putc( c, fp )/ fputc(c,fp) writes a character to the file associated with
the file pointer fp.
7 | P a g e
Exercises
*** READING FROM FILE *** Test.txt This is a test file 1) #include "stdafx.h" #include "stdlib.h" int main() { FILE *fp; char b[50],ch; fopen_s(&fp,"test.txt", "r"); if (!fp) { printf("File opening failed"); return EXIT_FAILURE; } fgets(b, sizeof b, fp); //puts(b); printf("%s", b); fclose(fp); return 0; }
2) #include "stdafx.h" int main() { FILE *fp; char b[50], ch; fopen_s(&fp, "test.txt", "r"); if (!fp) { printf("File opening failed"); return EXIT_FAILURE; } ch = fgetc(fp); while (ch != EOF)//OR (!feof(fp)) { printf("%c", ch); ch = fgetc(fp); } fclose(fp); return 0; }
Test.txt
This is a test file
line1
line2
line3
3) #include "stdafx.h" #include "stdlib.h" int main()
8 | P a g e
{ FILE *fp; char b[50], ch; fopen_s(&fp, "test.txt", "r"); if (!fp) { printf("File opening failed"); return EXIT_FAILURE; } while (!feof(fp)) { fgets(b, sizeof b, fp); //OR puts(b); printf("%s", b); } fclose(fp); return 0; }
4) #include "stdafx.h" #include "stdlib.h" int main() { FILE *fp; char b[50], ch; int nlines=0, nc = 0; fopen_s(&fp, "test.txt", "r"); if (!fp) { printf("File opening failed"); return EXIT_FAILURE; } ch = fgetc(fp); while (!feof(fp)) { if (ch == '\n') nlines++; nc++; ch = fgetc(fp); } printf("There are %d characters\n", nc); printf("There are %d lines \n", nlines-1); fclose(fp); return 0; }
*** WRITING TO A FILE *** 5) #include "stdafx.h" #include "stdlib.h" int main() { FILE *fp; fopen_s(&fp, "test1.txt", "w"); if (!fp) { printf("File opening failed"); return EXIT_FAILURE; } fprintf(fp, "This is testing for fprintf...\n");
9 | P a g e
fputs("This is testing for fputs...\n", fp); fclose(fp); return 0; }
10 | P a g e
6) #include "stdafx.h" #include "stdlib.h" int main() { FILE *fp; fopen_s(&fp, "test1.txt", "a"); if (!fp) { printf("File opening failed"); return EXIT_FAILURE; } fprintf(fp, "This is testing for ADDING...\n"); fputs("This is testing for ADDING a line...\n", fp); fclose(fp); return 0; }
7) writing to a file from keyboard #include "stdafx.h" #include "stdlib.h" int main() { FILE *fptr; int n; fopen_s(&fptr, "program.txt", "w"); if (!fptr) { printf("File opening failed"); return EXIT_FAILURE; } printf("Enter n: "); scanf_s("%d", &n); while (!feof(stdin)) { fprintf(fptr,"%4d", n); printf("Enter n: "); scanf_s("%d", &n); } fclose(fptr); return 0; }
11 | P a g e
*** write and read (w+) *** 8) #include "stdafx.h" #include "stdlib.h" //for EXIT_FAILURE int main() { FILE *fptr; char ch; fopen_s(&fptr, "program.txt", "w+"); if (!fptr) { printf("File opening failed"); return EXIT_FAILURE; } fprintf(fptr, "This is testing for w+"); rewind(fptr); ch = fgetc(fptr); // OR ch = getc(fptr); while (ch != EOF) //OR while(!feof(fptr)) { printf("%c", ch); // OR putchar(ch); ch = fgetc(fptr); // OR ch = getc(fptr); } fclose(fptr); return 0; }
OR 9) without rewind() function #include "stdafx.h" #include "stdlib.h" //for EXIT_FAILURE int main() { FILE *fptr; char ch; fopen_s(&fptr, "program.txt", "w"); if (!fptr) { printf("File opening failed"); return EXIT_FAILURE; } fprintf(fptr, "This is testing for w+"); fclose(fptr); fopen_s(&fptr, "program.txt", "r"); ch = fgetc(fptr); while(!feof(fptr)) { putchar(ch); ch = getc(fptr); } fclose(fptr); return 0; }
12 | P a g e
13 | P a g e
*** copying from one file to another file with converting characters to uppercase***
10)
#include "stdafx.h" #include "ctype.h" #include "stdlib.h" //for EXIT_FAILURE int main() { char ch, name[30]; FILE *lfPtr, *ufPtr; fopen_s(&lfPtr,"lower.txt", "w+"); fopen_s(&ufPtr, "upper.txt", "w"); if (!lfPtr) { printf("File opening failed"); return EXIT_FAILURE; } if (!ufPtr) { printf("File opening failed"); return EXIT_FAILURE; } printf("enter your name and surname: "); gets_s(name); fputs(name, lfPtr); rewind(lfPtr); //repositions the file pointer to the beginning of a stream ch = fgetc(lfPtr); while (!feof(lfPtr)) { fputc(toupper(ch), ufPtr); ch = fgetc(lfPtr); } fclose(lfPtr); fclose(ufPtr); return 0; }