C Programming - File Handling
C Programming - File Handling
C Programming - File Handling
File handling in C - opening and closing. Reading from and writing to files. Special file streams stdin, stdout & stderr. How we SHOULD read input from the user. What are STRUCTURES? What is dynamic memory allocation?
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 couldn't open the file.
FILE *fptr; char filename[]= "file2.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { fprintf (stderr, ERROR); /* DO SOMETHING */ }
We could also read numbers from a file using fscanf but there is a better way.
fgets takes 3 arguments, a string, a 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. Here's a complete "hello files".
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);
Reading loops
It is quite common to want to read every line in a program. The best way to do this is a while loop using fgets.
/* define MAXLEN at start using enum */ FILE *fptr; char tline[MAXLEN]; /* A line of text */ fptr= fopen ("sillyfile.txt","r"); /* check it's open */ while (fgets (tline, MAXLEN, fptr) != NULL) { printf ("%s",tline); // Print it } fclose (fptr);
fgets and stdin can be combined to get a safe way to get a line of input from the user
#include <stdio.h> int main() { const int MAXLEN=1000; char readline[MAXLEN]; fgets (readline,MAXLEN,stdin); printf ("You typed %s",readline); return 0; }
Structures in C
In C, we can create our own data types - FILE is an example of this. If programmers do a good job of this, the end user doesn't even have to know what is in the data type.
struct is used to describe a new data type. typedef is used to associate a name with it. int, double and char are types of variables. With struct you can create your own. It is a new way to extend the C programming language.
Typedef
Typedef allows us to associate a name with a structure (or other data type). Put typedef at the start of your program.
typedef struct line { int x1, y1; int x2, y2; } LINE;
line1 is now a structure of line type This is what was happening with all that FILE * stuff
This is a CAST sizeof(char) returns how we want (remember them) much memory a char n chars that forces the variable takes to the right type (not needed) This says in effect "grab me enough memory for 'n' chars"
Free
The free statement says to the computer "you may have the memory back again"
free(sieve);
essentially, this tells the machine that the memory we grabbed for sieve is no longer needed and can be used for other things again. It is _VITAL_ to remember to free every bit of memory you malloc