Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

File Writing

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Why Use a Disk?

If you've worked with computers very much, and if you've done some programming in other
languages, you know the importance of file storage for data. The typical computer system has
much less memory storage than hard disk storage. Your disk drive holds much more data than
can fit in your computer's RAM. The disk memory, because it is nonvolatile, lasts longer because
the disk retains its contents when you power-off your computer. Also, when your data changes,
you (or more important, your users) do not have to edit the program and look for a set of
assignment statements. Instead, the users run previously written programs that make changes to
the disk data.

Types of Disk File Access

Your programs can access files two ways: through sequential access or random access. Your
application determines the method you should choose. The access mode of a file determines how
you read, write, change, and delete data from the file. Some of your files can be accessed in both
ways, sequentially and randomly, as long as your programs are written properly and the data
lends itself to both types of file access.

NOTE
Your C compiler might offer additional ways to access disk files with a library
of specific I/O functions.

A sequential file must be accessed in the same order the file was written. This is analogous to
cassette tapes: You play music in the same order it was recorded. (You can quickly fast-forward
or rewind through songs that you do not want to listen to, but the order of the songs dictates what
you do to play the song you want.) It is difficult, and sometimes impossible, to insert data in the
middle of a sequential file. How easy is it to insert a new song in the middle of two other songs
on a tape? The only way to truly add or delete records from the middle of a sequential file is to
create a completely new file that combines both old and new songs.

It might seem that sequential files are limiting, but it turns out that many applications lend
themselves to sequential file processing.
Unlike with sequential files, you can access random access files in any order
you want. Think of data in a random access file as you would think of songs on
a compact disc or a record; you can go directly to any song you want without
having to play or fast-forward through the other songs. If you want to play the
first song, the sixth song, and then the fourth song, you can do so. The order of
play has nothing to do with the order in which the songs appear on the
recording.

Learning
Sequential File
Concepts

There are three operations you can perform on sequential disk files. You can

Create disk files

Add to disk files

Read from disk files

To open a file, you must call the fopen() function (for ''file open"). To close a file, call the
fclose() function. Here is the format of these two function calls:

filePtr = fopen(fileName, access);

and
fclose(filePtr);

The filePtr is a special type of pointer that points only to files, not to data variables. You
must define a file pointer with FILE , a definition in the stdio.h header file. The examples
that follow show you how to define a file pointer.

The value for access can be one of the mode values from Table 24.1. The updating access
modes (those with a plus sign) are used in random file processing.

Table 24.1: Possible access modes.


Mode Description
"r" Opens a file for reading
"w" Opens a file for writing (creates it)
"a" Opens a file for appending (adding to it)
"r+" Opens a file for update (reading and writing)
"w+" Opens a file for update (creates it, then allows reading and writing)
"a+" Opens a file for update (reads the entire file, or writes to the end of it)

Sometimes you see programs that contain a t or a b in the access mode, such as ''rt" or "wb+".
The t means text file and is the default mode; each of the access modes listed in Table 24.1 is
equivalent to using t after the access mode letter ("rt" is identical to "r", and so on). A text file
is an ASCII file, compatible with most other programming languages and applications. Text files
do not always contain text, in the word processing sense of the word. Any data you need to store
can go in a text file. Programs that read ASCII files can read data you create as C text files. The
b in the access mode means binary mode.

BINARY MODES
If you specify b inside the access mode rather than t, C creates or reads the file
in a binary format. Binary data files are "squeezed"that is, they take less space
than text files. The disadvantage of using binary files is that other programs
cannot always read the data files. Only C programs written to access binary files
(using the b access mode) can read and write to them. The advantage of binary
files is that you save disk space because your data files are more compact. Other
than the access mode in the fopen() function, you use no additional
commands to access binary files with your C programs.

The binary format is a system-specific file format. In other words, not all
computers can read a binary file created on another computer.

Here is a complete list of binary file access modes:

"rb" "wb" "ab" "ab+" "a+b" "wb+" "w+b" "ab+" "


a+b"

If you open a fil for writing (using access modes of "w", "wt", "wb", or "w+"), C creates the file.
If a file by that name already exists, C overwrites the old file with no warning. When opening
files, you must be careful that you do not overwrite existing data you want to save

Example

1. Suppose that you want to create a file for storing your house payment records for the last year.
Here are the first few lines in the program that would create a file called house.dat on your
disk:

#include <stdio.h>

main()
{
FILE *filePtr; // Declares a file pointer
filePtr = fopen(house.dat", "w"); // Creates the file

3. If you like, you can store a filename in a character array or point to it with a character pointer.
Each of the following sections of code is equivalent:

char fn[] = "house.dat"; // Filename in character array


filePtr = fopen(fn, "w"); // Creates the file
char *myfile="house.dat"; // Filename pointed to
filePtr = fopen(myfile, "w"); // Creates the file
/* Let the user enter the filename */
printf("What is the name of the household file? ");
gets(filename); // Filename must be an
// array or character pointer
filePtr = fopen(filename, "w"); // Creates the file

4. Check the return value from fopen() to ensure that the file opened properly. Here is code
after fopen() that checks for an error:

#include <stdio.h>

main()
{
FILE *filePtr; // Declares a file pointer
filePtr = fopen(''house.dat", "w"); // Creates the file
if (filePtr == NULL)
{ printf("Error opening file.\n"); }
else
{ /* Rest of output commands go here */ }

Here is a way you can open the two payroll files:

#include <stdio.h>
FILE *fileIn; // Input file
FILE *fileOut; // Output file

main()
{
fileIn = fopen("payroll.dat", "r"); // Existing file
fileOut = fopen("payroll.BAK", "w"); // New file

When you finish with these files, be sure to close them with these two fclose() function
calls:

fclose(fileIn);
fclose(fileOut);

Writing to a File

Any input or output function that requires a device performs input and output with files. You
have seen most of these already. The most common file I/O functions are

getc() and putc()


fprintf()

fgets() and fputs()

There are a few more, but the most common I/O function left that you have not seen is the
fscanf() function. fscanf() is to scanf() as fprintf() is to printf(). The only
difference between fscanf() and scanf() is its first parameter. The first parameter to
fscanf() must be a file pointer (or any C device, such as stdin and stdaux).

The following function reads three integers from a file pointed to by filePtr:

fscanf(filePtr, "%d %d %d", &num1, &num2, &num3);


As with scanf(), you do not have to specify the & before array variable names. The following
fscanf() reads a string from the disk file:

fscanf(filePtr, "%s", name);

Writes five names to a disk file */


#include <stdio.h>

FILE *fp;

main()
{
fp = fopen(''NAMES.DAT", "w"); /* Creates a new file */

fputs("Michael Langston\n", fp);


fputs("Sally Redding\n", fp);
fputs("Jane Kirk\n", fp);
fputs("Stacy Grady\n", fp);
fputs("Paula Hiquet\n", fp);

fclose(fp); /* Release the file */


return 0;
}

char fn[] = "house.dat"; // Filename in character array


filePtr = fopen(fn, "w"); // Creates the file
char *myfile="house.dat"; // Filename pointed to
filePtr = fopen(myfile, "w"); // Creates the file
/* Let the user enter the filename */
printf("What is the name of the household file? ");
gets(filename); // Filename must be an
// array or character pointer
filePtr = fopen(filename, "w"); // Creates the file

/* Filename: C24WR2.C
Writes 1 to 100 to a disk file */
#include <stdio.h>

FILE *fp;

main()
{
int ctr;
fp = fopen("NUMS. 1", "wt"); /* Creates a new file */
if (fp == NULL)
{ printf("Error opening file.\n"); }

else
{ for (ctr=1; ctr<101; ctr++)
{ fprintf(fp, %d ", ctr); } /* Writes the data */
}
fclose(fp);
return 0;
}

APPENDING NAME TO FILE:


main()
{
fp = fopen("NAMES.DAT", "a"); // Adds to file

fputs("Johnny Smith\n", fp);


fputs("Laura Hull\n", fp);
fputs("Mark Brown\n", fp);

fclose(fp); // Release the file


return 0;
}
Reading from a File

As soon as the data is in a file, you must be able to read that data. You must open the file in a
read access mode. There are several ways to read data. You can read character data a character at
a time or a string at a time. The choice depends on the format of the data. If you stored numbers
using fprintf(), you might want to use a mirror-image fscanf() to read the data.

Files you open for read access (using ''r", "rt", and "rb") must exist already, or C gives you an
error. You cannot read a file that does not exist. fopen() returns NULL if the file does not exist
when you open it for read access
another event happens when reading files. Eventually, you read all the data. Subsequent reading
produces errors because there is no more data to read. C provides a solution to the end-of-file
occurrence. If you attempt to read from a file that you have completely read the data from, C
returns the value EOF, defined in stdio.h. To find the end-of-file condition, be sure to check
for EOF when performing input from files.

1. This program asks the user for a filename and prints the contents of the file to the screen. If
the file does not exist, the program displays an error message:

/* Filename: C24RE1.C
Reads and displays a file */
#include <stdio.h>

FILE *fp;

main()
{
char filename[12]; // Holds user's filename
int inChar; // Input character

printf(What is the name of the file you want to see? ");


gets(filename);
if ((fp=fopen(filename, "r"))==NULL)
{ printf("\n\n That file does not exist \n");
exit(); // Exits program
}

inChar = getc(fp); // Reads first character


while (inChar != EOF)
{ putchar(inChar);
inChar = getc(fp);
}
fclose(fp);
return 0;
}

Notice that the program reads the input character in two places. It is possible, although rare, that
a file with no data could exist. In such a file, the first character read would result in the end-of-
file condition. Therefore, this program reads the first character and prints it as long as it is not
EOF.

Although the program is written to help illustrate file input, most C programmers combine the
file input with the test for EOF. This might seem like too much to do at once, but it is so
common in C programs that you should become familiar with the algorithm. Here is a rewritten
version of the previous program's I/O routine that is more common:

while ((inChar = getc(fp)) != EOF) /* Reads first */


{ putchar(inChar); } /* character */
struct items{
int key; //ID field
char name[30];
float salary;
};

struct items item[MAX];

FILE *fp2;

void create_file(){
fp2 = fopen("customers2.txt","w");
fclose(fp2);
}

/**************** FILE WRITING FUNCTION ***********************/


void filewrite2(struct items item[],int p){

int i;

fp2 = fopen("customers2.txt","r+");
i=0;
while (i < p){
fwrite(&item[i], sizeof(item[0]), 1, fp2); // Add structure
i++;
}

fclose(fp2) ;
}
void fileprint2(int p)
{
struct items tempItem[MAX];
FILE *fp2;
int s,i;
s = sizeof(tempItem[0]);
i=0;
if ((fp2 = fopen("customers2.txt","r+"))==NULL) //open file for random read
fread() reads properly */
{
printf("file does not exist");
}
do
{ if(fread(&tempItem[i], sizeof(tempItem[p]), p,fp2)!=s)
{ if(feof(fp2)) /* If EOF, quit reading */
{ break; }
}
i++;
}while(i<p);
// while (!feof(fp2));

fclose(fp2);
i=0;
while (i<p){
printf("\n ID : %d\n", tempItem[i].key);
printf("\nName : %s\n", tempItem[i].name);
printf("Salary: %.2f\n", tempItem[i].salary);
i++;
}
}

int call_delete()
{
int z;

z = remove("customers2.txt");
return z;
}

/* Filename: C24RE1.C
Reads and displays a file */
#include <stdio.h>

FILE *fp;

main()
{
char filename[12]; // Holds user's filename
int inChar; // Input character

printf(''What is the name of the file you want to see? ");


gets(filename);

if ((fp=fopen(filename, "r"))==NULL)
{ printf("\n\n That file does not exist \n");
exit(); // Exits program
}

inChar = getc(fp); // Reads first character


while (inChar != EOF)
{ putchar(inChar);
inChar = getc(fp);
}
fclose(fp);
return 0;
}

You might also like