<< 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

how does Neisseria cause meningitis
Nyibol Reply
what is microbiologist
Muhammad Reply
what is errata
Muhammad
is the branch of biology that deals with the study of microorganisms.
Ntefuni Reply
What is microbiology
Mercy Reply
studies of microbes
Louisiaste
when we takee the specimen which lumbar,spin,
Ziyad Reply
How bacteria create energy to survive?
Muhamad Reply
Bacteria doesn't produce energy they are dependent upon their substrate in case of lack of nutrients they are able to make spores which helps them to sustain in harsh environments
_Adnan
But not all bacteria make spores, l mean Eukaryotic cells have Mitochondria which acts as powerhouse for them, since bacteria don't have it, what is the substitution for it?
Muhamad
they make spores
Louisiaste
what is sporadic nd endemic, epidemic
Aminu Reply
the significance of food webs for disease transmission
Abreham
food webs brings about an infection as an individual depends on number of diseased foods or carriers dully.
Mark
explain assimilatory nitrate reduction
Esinniobiwa Reply
Assimilatory nitrate reduction is a process that occurs in some microorganisms, such as bacteria and archaea, in which nitrate (NO3-) is reduced to nitrite (NO2-), and then further reduced to ammonia (NH3).
Elkana
This process is called assimilatory nitrate reduction because the nitrogen that is produced is incorporated in the cells of microorganisms where it can be used in the synthesis of amino acids and other nitrogen products
Elkana
Examples of thermophilic organisms
Shu Reply
Give Examples of thermophilic organisms
Shu
advantages of normal Flora to the host
Micheal Reply
Prevent foreign microbes to the host
Abubakar
they provide healthier benefits to their hosts
ayesha
They are friends to host only when Host immune system is strong and become enemies when the host immune system is weakened . very bad relationship!
Mark
what is cell
faisal Reply
cell is the smallest unit of life
Fauziya
cell is the smallest unit of life
Akanni
ok
Innocent
cell is the structural and functional unit of life
Hasan
is the fundamental units of Life
Musa
what are emergency diseases
Micheal Reply
There are nothing like emergency disease but there are some common medical emergency which can occur simultaneously like Bleeding,heart attack,Breathing difficulties,severe pain heart stock.Hope you will get my point .Have a nice day ❣️
_Adnan
define infection ,prevention and control
Innocent
I think infection prevention and control is the avoidance of all things we do that gives out break of infections and promotion of health practices that promote life
Lubega
Heyy Lubega hussein where are u from?
_Adnan
en français
Adama
which site have a normal flora
ESTHER Reply
Many sites of the body have it Skin Nasal cavity Oral cavity Gastro intestinal tract
Safaa
skin
Asiina
skin,Oral,Nasal,GIt
Sadik
How can Commensal can Bacteria change into pathogen?
Sadik
How can Commensal Bacteria change into pathogen?
Sadik
all
Tesfaye
by fussion
Asiina
what are the advantages of normal Flora to the host
Micheal
what are the ways of control and prevention of nosocomial infection in the hospital
Micheal
what is inflammation
Shelly Reply
part of a tissue or an organ being wounded or bruised.
Wilfred
what term is used to name and classify microorganisms?
Micheal Reply
Binomial nomenclature
adeolu
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