Accessing a file is a three step process:
· Opening a connection to a file
· Reading/writing data from/to the file
· Closing the connection
Opening a Connection to a File
In order to use a file on a disk you must establish a connection with it. A connection can be established using the fopen function. The function takes the general form:
fopen(file_name, access_mode)
The file_name is the name of the file to be accessed and it may also include the path. The access_mode defines whether the file is open for reading, writing or appending data. Table 9.1 summarises the access modes supported by fopen function.
The following code opens a file named “my file.txt” in the current directory for appending data:
FILE *fp;
fp = fopen("my file.txt", "a");
The function fopen returns a pointer (referred as the file pointer) to the structure6 FILE which is
defined in the stdio.h headier file. When you open a file it would be better to make sure that the
operation is successful. If the establishment of a connection is successful the function returns a pointer
to the file. If an error is encountered while establishing a connection the functions returns NULL.
Closing the Connection to a File
After a connection to a file is established it can be used to read or write data. When all the file processing is over the connection should be closed. Closing the connection is important as it writes any remaining data in the buffer to the output file. The function fclose is used to close the file. For example:
fclose(fp)
When closing the file the file pointer “fp” is used as an argument of the function. When a file is successfully closed the function fclose returns a zero and any other value indicates an error.
Reading Data from a File
When reading data from a ASCII file you can either read one character or one string at a time. Reading Characters from a File To read one character at a time you can use the getc function. It takes the form:
getc(file_pointer)
You can assign the output of the function getc to an int or char variable.
Example 9.1 – Write a program to read the file “my file.txt” which has the message:
Hello World!
This is my first file
The following program reads the file “my file.txt” one character at a time and displays it on the screen.
/* Program-9.1 */
#include <stdio.h>
int main()
{
FILE *fp;
char c;
fp = fopen("my text.txt", "r"); //open read-only
if(fp != NULL)
{
c = getc(fp); //read the 1st character
while ( c != EOF) //if not the end of file
{
printf("%c",c);
c= getc(fp); //read next character
fclose(fp); //close the file
}
else
printf("\nError while opening file...");
return 0;
}
Execution of Program-9.1 will display
Hello World!
This is my first file
In Program-9.1 a connection is first established to the file. Then the expression if(fp != NULL) evaluates whether the connection is successful. If it is not successful the program will display the message “Error while opening file...” If it is successful it reads the first character from the file. If the character is not the end of the file (indicated by the End Of File (EOF) mark) it displays the character. Then the program continues to read the rest of the characters in the file until it finds the EOF mark. Afterwards the connection to the file is closed using the fclose function.
Reading a String from a File
In real-life applications it is more useful to read one string at a time rather than one character. With every read, the program has to check for the line feed (LF) character so it can find the end of each string. Also it must check for the EOF mark which comes at the end of the file . The fgets function can be used to read a string at a time. The function generally takes the form:
fgets(string, max_characters, file_pointer)
The “string” is a character array (also called a character buffer) and “max_characters” define the maximum number of characters to read form a line. The function fgets returns a char pointer. It returns NULL if EOF mark is encountered. One deficiency in fgets is that it can only read to a fixed character buffer, therefore you need to know in advance the maximum number of characters in a string.
Example 9.2 – Modify Program-9.1 such that it uses the fgets function instead of fgetc function.
Suppose the file does not have more than 100 characters in a line.
/* Program-9.2 */
#include <stdio.h>
int main()
{
FILE *fp;
char buffer[100]; //char array with 100 elements
char *result; // hold the result of the fgets function
fp = fopen("my text.txt", "r"); //open read-only
if(fp != NULL)
{
result = fgets(buffer, 100, fp); //read the 1st string
while(result != NULL) //if not the end of file
{
printf("%s",buffer);
result = fgets(buffer, 100, fp); //read the next string
}
fclose(fp); //close the file
}
else
printf("\nError while opening file");
return 0;
}
Writing Data to a File
You can also write data to file either one character at a time or a string at a time. Writing Character to a File
To write a character to a file the putc function can be used.
It has the form:
putc(c, fp)
where c is the character while fp is the file pointer. It returns an int value which indicates the success or the failure of the function. It returns the int value of the character if it is successful, if not it returns EOF mark.
Example 9.3 – Write a C program to store the message “Introduction C Programming” in a file named
“message.txt”.
Program-9.3 is an implementation of the above requirement. The function putc is used to write characters in the message to the file. To find the number of characters in the message the strlen string and the pointer is incremented by one memory location at a time.
/* Program-9.3 */
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
int i; //loop counter
char *message;
message = "Introduction C Programming";
fp = fopen("c:\\message.txt", "w"); //open for writing
if(fp != NULL) //if success
{
for (i =0 ; i < strlen(message);i++)
putc(*(message+i),fp); //write character pointed by pointer
fclose(fp); //close the file
}
else
printf("\nError while opening file");
return 0;
}
Writing a String to a File
The advantage of putc is that it allows you to control every byte that you write into the file. However sometimes you may want to write one string at a time. Two functions , namely fputs and fprintf can be used for this purpose. The fprintf function is identical to the printf function only difference being that it writes to a file rather than to the screen. The format of each function is:
fputs(string, file_pointer)
fprintf(file_pointer, “%s”, string)
Exercise 9.1 – Modify Program-9.3 such that it uses the fputs rather than the fputc function to write the message to the file .
Exercise 9.2 – Develop a simple telephone directory which saves your friends contact information in a file named directory.txt. The program should have a menu similar to the following:
----------------Menu-------------------------
1. Add new friend.
2. Display contact info.
3. Exit
------------------------------------------------
Enter menu number:
When you press “1” it should request you to enter following data:
---------New friend info--------
Name : Saman
Phone-No: 011-2123456
e-Mail : saman@cse.mrt.ac.lk
After adding new contact information it should again display the menu. When you press “2” it should display all the contact information stored in the directory.txt file as follows:
--------------Contact info---------------
Name Tel-No e-Mail
Kamala 077-7123123 kamala@yahoo.com
Kalani 033-4100101 kalani@gmail.com
Saman 011-2123456 saman@cse.mrt.ac.lk
-----------------------------------------
No comments:
Post a Comment