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

or

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

or

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

Discuss the differences between taste and flavor, including how other sensory inputs contribute to our  perception of flavor.
John Reply
taste refers to your understanding of the flavor . while flavor one The other hand is refers to sort of just a blend things.
Faith
While taste primarily relies on our taste buds, flavor involves a complex interplay between taste and aroma
Kamara
which drugs can we use for ulcers
Ummi Reply
omeprazole
Kamara
what
Renee
what is this
Renee
is a drug
Kamara
of anti-ulcer
Kamara
Omeprazole Cimetidine / Tagament For the complicated once ulcer - kit
Patrick
what is the function of lymphatic system
Nency Reply
Not really sure
Eli
to drain extracellular fluid all over the body.
asegid
The lymphatic system plays several crucial roles in the human body, functioning as a key component of the immune system and contributing to the maintenance of fluid balance. Its main functions include: 1. Immune Response: The lymphatic system produces and transports lymphocytes, which are a type of
asegid
to transport fluids fats proteins and lymphocytes to the blood stream as lymph
Adama
what is anatomy
Oyindarmola Reply
Anatomy is the identification and description of the structures of living things
Kamara
what's the difference between anatomy and physiology
Oyerinde Reply
Anatomy is the study of the structure of the body, while physiology is the study of the function of the body. Anatomy looks at the body's organs and systems, while physiology looks at how those organs and systems work together to keep the body functioning.
AI-Robot
what is enzymes all about?
Mohammed Reply
Enzymes are proteins that help speed up chemical reactions in our bodies. Enzymes are essential for digestion, liver function and much more. Too much or too little of a certain enzyme can cause health problems
Kamara
yes
Prince
how does the stomach protect itself from the damaging effects of HCl
Wulku Reply
little girl okay how does the stomach protect itself from the damaging effect of HCL
Wulku
it is because of the enzyme that the stomach produce that help the stomach from the damaging effect of HCL
Kamara
function of digestive system
Ali Reply
function of digestive
Ali
the diagram of the lungs
Adaeze Reply
what is the normal body temperature
Diya Reply
37 degrees selcius
Xolo
37°c
Stephanie
please why 37 degree selcius normal temperature
Mark
36.5
Simon
37°c
Iyogho
the normal temperature is 37°c or 98.6 °Fahrenheit is important for maintaining the homeostasis in the body the body regular this temperature through the process called thermoregulation which involves brain skin muscle and other organ working together to maintain stable internal temperature
Stephanie
37A c
Wulku
what is anaemia
Diya Reply
anaemia is the decrease in RBC count hemoglobin count and PVC count
Eniola
what is the pH of the vagina
Diya Reply
how does Lysin attack pathogens
Diya
acid
Mary
I information on anatomy position and digestive system and there enzyme
Elisha Reply
anatomy of the female external genitalia
Muhammad Reply
Organ Systems Of The Human Body (Continued) Organ Systems Of The Human Body (Continued)
Theophilus Reply
what's lochia albra
Kizito
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




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?

Ask