Files in C Programming
Files in C Programming
An example of fclose is
fclose(fp);
To work with text input and output, you use fprintf
and fscanf, both of which are similar to their
friends printf and scanf except that you must pass
the FILE pointer as first argument. For example:
FILE *fp;
fp=fopen("c:\\test.txt", "w");
fprintf(fp, "Testing...\n");
It is also possible to read (or write) a single
character at a time--this can be useful if you wish
to perform character-by-character input (for
instance, if you need to keep track of every piece
of punctuation in a file it would make more sense
to read in a single character than to read in a string
at a time.) The fgetc function, which takes a file
pointer, and returns an int, will let you read a
single character from a file:
3
int fgetc (FILE *fp);
Notice that fgetc returns an int. What this actually
means is that when it reads a normal character in
the file, it will return a value suitable for storing in
an unsigned char (basically, a number in the range
0 to 255). On the other hand, when you're at the
very end of the file, you can't get a character
value--in this case, fgetc will return "EOF", which is
a constant that indicates that you've reached the
end of the file. To see a full example using fgetc in
practice, take a look at the example here.
4
size_t fread(void *ptr, size_t size_of_elements,
size_t number_of_elements, FILE *a_file);
5
arrays. E.g., if you have a variable of a struct type
with the name a_struct, you can use
sizeof(a_struct) to find out how much memory it is
taking up.
e.g.,
sizeof(int);
For example,
6
FILE *fp;
fp=fopen("c:\\test.bin", "wb");
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);