Slides3 05
Slides3 05
FILE *fptr;
char filename[]= "file2.dat";
fptr= fopen (filename,"w");
if (fptr == NULL) {
fprintf (stderr,
“ERROR”);
/* DO SOMETHING */
}
Modes for opening files
• The second argument of fopen is the mode in
which we open the file. There are three
• "r" opens a file for reading
• "w" opens a file for writing - and writes over all
previous contents (deletes the file so be
careful!)
• "a" opens a file for appending - writing on the
end of the file
The exit() function
• Sometimes error checking means we want
an "emergency exit" from a program. We
want it to stop dead.
• In main we can use "return" to stop.
• In functions we can use exit to do this.
• Exit is part of the stdlib.h library
exit(-1);
in a function is exactly the same as
return -1;
in the main routine
Writing to a file using fprintf
• fprintf works just like printf and sprintf except
that its first argument is a file pointer.
FILE *fptr;
fptr= fopen ("file.dat","w");
/* Check it's open */
fprintf (fptr,"Hello World!\n");
FILE *fptr;
char line [1000];
/* Open file and check it is open */
while (fgets(line,1000,fptr) != NULL) {
printf ("Read line %s\n",line);
}
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);
Great Muck-Ups in C #72 of 100
• We use the file pointer to close the file - not the
name of the file
FILE *fptr;
fptr= fopen ("myfile.dat","r");
/* Read from file */
fclose ("myfile.dat");
/* Ooops - that's wrong */
Three special streams
• Three special file streams are defined in the
stdio.h header
• stdin reads input from the keyboard
• stdout send output to the screen
• stderr prints errors to an error device
(usually also the screen)
• What might this do:
int main()
{ line1 is now a structure of line type
LINE line1; This is what was happening with all
that FILE * stuff
}
Accessing parts of a struct
• To access part of a structure we use the dot
notation
LINE line1;
line1.x1= 3;
line1.y1= 5;
line1.x2= 7;
if (line1.y2 == 3) {
printf ("Y co-ord of end is 3\n");
}
What else can we do with
structs?
• We can pass and return structs from
functions. (But make sure the function
prototype is _AFTER_ the struct is
declared)
typedef struct line {
int x1,y1;
int x2,y2;
} LINE;
int main()
{
/* Main goes here */
}
This is a CAST
(remember them) we want sizeof(char) returns how
that forces the variable n chars much memory a char
to the right type (not takes
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);