|
file handling in C is different from C++ and is a bit awkward especially if you have missed the classes, funny how no one has realized you are talking about C.
File handling allows you store data in files that can be read - it is like when you have a spread sheet or a database you store the information on a seperate file. A file is simply a machine decipherable storage media where programs and data are stored for machine usage.Essentially there are two kinds of files that programmers deal with text files and binary files.
A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time.
A binary file is no different to a text file. It is a collection of bytes. In C a byte and a character are equivalent. So a binary file is also referred to as a character stream.
What you need to open a file in C is use a type called the file pointer this is found in the stdio header file so here is an example this will open a file called stuff.txt and write a line of text ten times.
FILE *fp; /* this is the file pointer */
char stuff[25];
int index;
fp = fopen("stuff.txt","w"); /* open for writing */
strcpy(stuff,"This is an example line.");
for (index = 1; index <= 10; index++)
/* this writes to the file the text */
fprintf(fp,"%s Line number %d
", stuff, index);
fclose(fp); /* close the file before exiting */
The type FILE is used for a file variable and is defined in the stdio.h file. It is used to define a file pointer for use in file operations. Before writing to a file, it must opened. What this really means is that the system must be told that the program is to write to a file and what the file name is. This is done with the fopen() function. The file pointer, fp in this case, points to the file and two arguments are required in the parentheses, the file name first, followed by the file type. the second parameter is the file attribute and can be any of three letters, r, w, or a, and must be lower case which are read, write and append.
|