<< Chapter < Page Chapter >> Page >
fp = fopen(filename, "r"); if(fp == NULL){ fprintf(stderr, "can't open file\n");return; }


while(fgets(line, max, fp) != NULL) {... process input ... }if(ferror(fp)) fprintf(stderr, "error reading input\n");


fprintf(fp, "%d %d %d\n", a, b, c); if(ferror(fp))fprintf(stderr, "output write error\n");

Error messages are much more useful, however, if they include a bit more information, such as the name of the file for which the operation is failing, and if possible why it is failing. For example, here is a more polite way to report that a file could not be opened:

#include<stdio.h>/* for fopen */ #include<errno.h>/* for errno */ #include<string.h>/* for strerror */ fp = fopen(filename, "r");if(fp == NULL) {fprintf(stderr, "can't open %s for reading: %s\n", filename, strerror(errno));return; }

errno is a global variable, declared in<errno.h>, which may contain a numeric code indicating the reason for a recent system-related error such as inability to open a file. The strerror function takes an errno code and returns a human-readable string such as “No such file” or “Permission denied”.

An even more useful error message, especially for a “toolkit” program intended to be used in conjunction with other programs, would include in the message text the name of the program reporting the error.

Access to binary files

Write data to binary files

size_t fwrite(void *buf, size_t sz, size_t n, FILE *fp)

This function writes to file associated with fp, num number of objects, each object size bytes long, from the buffer pointed to by buffer.

Return value: It returns the number of objects written. This value will be less than num only if an output error as occurred.

The void pointer is a pointer that can point to any type of data without the use of a TYPE cast (known as a generic pointer). The type size_t is a variable that is able to hold a value equal to the size of the largest object surported by the compiler.

As a simple example, this program write an integer value to a file called MYFILE using its internal, binary representation.

#include<stdio.h>/* header file */ #include<stdlib.h>void main(void) {FILE *fp; /* file pointer */ int i;/* open file for output */ if ((fp = fopen("myfile", "w"))==NULL){printf("Cannot open file \n"); exit(1);} i=100;if (fwrite(&i, 2, 1, fp) !=1){ printf("Write error occurred");exit(1); }fclose(fp); }

Read data from binary files

size_t fread(void *buf, size_t sz, size_t n, FILE *fp)

fread reads up to n objects, each of size sz, from the file specified by fp, and copies them to the buffer pointed to by buf. It reads them as a stream of bytes, without doing any particular formatting or other interpretation. (However, the default underlying stdio machinery may still translate newline characters unless the stream is open in binary or "b" mode).

Return value: returns the number of items read. It returns 0 (not EOF) at end-of-file.

#include<stdio.h>int main() { FILE *file;char c[30]; /* make sure it is large enough to hold all the data! */char *d; int n;file = fopen("numbers.txt", "r"); if(file==NULL) {printf("Error: can't open file.\n"); return 1;} else {printf("File opened successfully.\n");n = fread(c, 1, 10, file); /* passing a char array, reading 10 characters */c[n] = '\0'; /* a char array is only astring if it has the null character at the end */printf("%s\n", c); /* print out the string */ printf("Characters read: %d\n\n", n);fclose(file); /* to read the file from the beginning, */ /* we need to close and reopen the file */file = fopen("numbers.txt", "r"); n = fread(d, 1, 10, file);/* passing a char pointer this time - 10 is irrelevant */ printf("%s\n", d);printf("Characters read: %d\n\n", n); fclose(file);return 0; }}
Got questions? Get instant answers now!

Questions & Answers

what does nano mean?
Anassong Reply
nano basically means 10^(-9). nanometer is a unit to measure length.
do you think it's worthwhile in the long term to study the effects and possibilities of nanotechnology on viral treatment?
Damian Reply
absolutely yes
how to know photocatalytic properties of tio2 nanoparticles...what to do now
Akash Reply
it is a goid question and i want to know the answer as well
characteristics of micro business
for teaching engĺish at school how nano technology help us
Do somebody tell me a best nano engineering book for beginners?
s. Reply
what is fullerene does it is used to make bukky balls
Devang Reply
are you nano engineer ?
fullerene is a bucky ball aka Carbon 60 molecule. It was name by the architect Fuller. He design the geodesic dome. it resembles a soccer ball.
what is the actual application of fullerenes nowadays?
That is a great question Damian. best way to answer that question is to Google it. there are hundreds of applications for buck minister fullerenes, from medical to aerospace. you can also find plenty of research papers that will give you great detail on the potential applications of fullerenes.
what is the Synthesis, properties,and applications of carbon nano chemistry
Abhijith Reply
Mostly, they use nano carbon for electronics and for materials to be strengthened.
is Bucky paper clear?
so some one know about replacing silicon atom with phosphorous in semiconductors device?
s. Reply
Yeah, it is a pain to say the least. You basically have to heat the substarte up to around 1000 degrees celcius then pass phosphene gas over top of it, which is explosive and toxic by the way, under very low pressure.
Do you know which machine is used to that process?
how to fabricate graphene ink ?
for screen printed electrodes ?
What is lattice structure?
s. Reply
of graphene you mean?
or in general
in general
Graphene has a hexagonal structure
On having this app for quite a bit time, Haven't realised there's a chat room in it.
what is biological synthesis of nanoparticles
Sanket Reply
what's the easiest and fastest way to the synthesize AgNP?
Damian Reply
types of nano material
abeetha Reply
I start with an easy one. carbon nanotubes woven into a long filament like a string
many many of nanotubes
what is the k.e before it land
what is the function of carbon nanotubes?
I'm interested in nanotube
what is nanomaterials​ and their applications of sensors.
Ramkumar Reply
what is nano technology
Sravani Reply
what is system testing?
preparation of nanomaterial
Victor Reply
how did you get the value of 2000N.What calculations are needed to arrive at it
Smarajit Reply
Privacy Information Security Software Version 1.1a
Berger describes sociologists as concerned with
Mueller Reply
Got questions? Join the online conversation and get instant answers!
QuizOver.com Reply

Get the best Algebra and trigonometry course in your pocket!

Source:  OpenStax, Introduction to computer science. OpenStax CNX. Jul 29, 2009 Download for free at http://cnx.org/content/col10776/1.1
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Introduction to computer science' conversation and receive update notifications?